如何使用JavaScript 对字符串进行 HTML 编码

本教程提供了一些用于对没有 XSS 漏洞的字符串进行 HTML 编码的方法。

这是一个以某种方式减少 XSS 机会的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
  </head>
  <body>
    <div id="encoded"></div>
    <div id="decoded"></div>
    <script>
      let string1 = 'Html & Css & Javascript';
      let string2 = "Html &amp; Css &amp; Javascript";
      $(document).ready(function() {
          $("#encoded").text(htmlEncode(string1));
          $("#decoded").text(htmlDecode(string2));
        });
      function htmlDecode(value) {
        return $("<textarea/>").html(value).text();
      }
      function htmlEncode(value) {
        return $('<textarea/>').text(value).html();
      }
    </script>
  </body>
</html>

在 htmlEncode 函数中,设置了元素的innerText,并检索了编码的innerHTML。
元素的innerHTML 值在检索innerText HTMLDecode 函数上设置。

<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
  </head>
  <body>
    <textarea rows="6" cols="50" name="normalTXT" id="textId">
    </textarea>
    <button onclick="convert()">Convert</button>
    <br>
    <URL>Encoding in URL:
      <input width="500" type="text" name="URL-ENCODE" id="URL-ENCODE">
      <br>
    </URL>
    <HTML>Encoding in HTML:
    <input type="text" name="HTML-ENCODE" id="HTML-ENCODE">
    <br>
    </HTML>
    <script>
      function htmlEncode(value) {
        //在内存中创建一个 div,设置它的内部文本。 jQuery 将自动编码。
        //然后将编码的内容取出。 该 div 永远不会存在于页面上。
        return $('<div/>').text(value).html().replace(/&/g, '%26');
      }
      function htmlDecode(value) {
        return $('<div/>').html(value).text();
      }
      function convert() {
        let text = document.getElementById('textId');
        let HTMLencoded = (text.value);
        document.getElementById('HTML-ENCODE').value = HTMLencoded;
        let urlEncode = htmlEncode(text.value);
        $("#URL-ENCODE").val(urlEncode);
      }
    </script>
  </body>
</html>

这种方法在很多场景下都能正常工作,但在某些情况下,你最终会遇到 XSS 漏洞。

对于上述函数,请考虑以下字符串:

htmlDecode("<img src='dummy' onerror='alert(/xss/)'>");

该字符串包含一个未转义的 HTML 标记,因此 htmlDecode 函数将运行字符串中指定的 JavaScript 代码,而不是解码。
为了避免这种情况,我们可以使用所有主要浏览器都支持的 DOMParser:

function htmlDecode(input) {
  let doc = new DOMParser().parseFromString(input, "text/html");
  return doc.documentElement.textContent;
}
alert(htmlDecode("<img src='img.jpg'&gt;")); //"<img src='myimage.jpg'>"
alert(htmlDecode("<img src='dummy' onerror='alert(/xss/)'>")); //""

该函数不会运行任何 JavaScript 代码作为副作用。
任何 HTML 标签都将被忽略,因为只会返回文本内容。

存在另一种有用且快速的方法,它也对引号进行编码:

function htmlEscape(str) {
  return str
    .replace(/&/g, '&')
    .replace(/'/g, "'")
    .replace(/"/g, '"')
    .replace(/>/g, '>')   
    .replace(/</g, '<');    
}
//解码函数
function htmlUnescape(str) {
  return str
    .replace(/"/g, '"')
    .replace(/'/g, "'")
    .replace(/&/g, '&')
    .replace(/</g, '<')
    .replace(/>/g, '>');
}

要转义正斜杠/出于反 XSS 安全目的,请使用以下命令:

.replace(/\//g, '/');

replace() 方法

replace() RegExp 方法用另一个字符串替换指定的字符串。

该方法有两个参数,第一个是要替换的字符串,第二个是从第一个字符串替换的字符串。
可以给第二个字符串一个空字符串,以便删除要替换的文本。

日期:2020-06-02 22:16:21 来源:oir作者:oir