【问题标题】:Prevent JQuery loaded example script from executing防止执行 JQuery 加载的示例脚本
【发布时间】:2017-03-10 15:31:01
【问题描述】:

我有一个页面,我希望它将描述它的 javascript 转储到 <code> 块中。问题是如果我使用$('pre code').html(data);,浏览器会解释脚本字符串文字中的标签并且格式会中断。相反,如果我使用$('pre code').text(data);,那么我的脚本将被执行,导致页面被渲染两次并复制了一些元素。

我知道这是一个奇怪的用例,但是这种问题有什么规范的解决方案吗?我目前的解决方案只是渲染盒子并同时执行脚本。

$.get("index.js", function(data, status)
{
    //Populate the code box and rn the page javascript at the same time
    //It seems to be impossible to set the text without making the javascript execute
    $('pre code').text(data);
    $('pre code').each(function(i, block) {
        hljs.highlightBlock(block);
    });
});

【问题讨论】:

    标签: javascript jquery escaping xss


    【解决方案1】:

    jQuery.get() 调用上将dataType 属性设置为text

    $.get("index.js", function(data, status){
        $('pre code').html(data);
    },"text"); // add this
    

    dataType 属性是:

    服务器预期的数据类型。默认值:智能猜测(xml、json、脚本、文本、html)。

    不是一个很好的演示,因为无论如何都不会执行任何操作,but here's the example above 将 jQuery 库作为纯文本获取

    【讨论】:

      【解决方案2】:

      Pre 用于多行代码,code 用于单行代码 sn-ps。这不完全是您要查找的代码,但它说明了一个示例。代码标签中不保留空格。因此,您只需要一个 pre 标签来显示所有代码行。此外,非常重要,您将 替换为 &gt 和 &lt,否则您的 JavaScript 文件中的任何内联 HTML 都将被执行(或者您可以只使用 .text 函数)。

      <pre></pre>
      
      <code>
      tset
      stest
      tset
      </code>
      
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
      <script>
      
      $.get("test.js",function (data) {
          $("pre").html(data.replace(/\</g,"&lt;").replace(/\>/g,"&gt;"));
      });
      
      </script>
      

      【讨论】:

        猜你喜欢
        • 2018-02-08
        • 2015-07-08
        • 2012-12-21
        • 1970-01-01
        • 2011-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-21
        相关资源
        最近更新 更多