开发者

Javascript code example copied into a pre-tag gets executed

开发者 https://www.devze.com 2023-03-25 16:42 出处:网络
I\'m trying to add a piece of javascript code to a certain <div>. I enclosed the code in pre and code tags, but when I actually run this the code gets executed. Obviously, that\'s not what I wan

I'm trying to add a piece of javascript code to a certain <div>. I enclosed the code in pre and code tags, but when I actually run this the code gets executed. Obviously, that's not what I want at all.

    var code = '<pre><code><script type="text/javascript" src="http://source.com/test.js"><\/script>\n';
    code = code + '<script type="text/javascript">\n';
    code = code + '\tadimp.id = ' + 1 + ';\n';
    code = code + '\tadimp.type = ' + 1 + ';\n';
 开发者_运维知识库   code = code + '\tadimp.generate();\n';
    code = code + '<\/script></code></pre>';

    $("#code").html(code);


You should use &lt; and &gt; for < and > in this case. Try this

var code = '<pre><code>&lt;script type="text/javascript" src="http://source.com/test.js"&gt;&lt;\/script&gt;\n';
    code = code + '&lt;script type="text/javascript"&gt;\n';
    code = code + '\tadimp.id = ' + 1 + ';\n';
    code = code + '\tadimp.type = ' + 1 + ';\n';
    code = code + '\tadimp.generate();\n';
    code = code + '&lt;\/script&gt;</code></pre>';

 $("#code").html(code);


Surprise! You just manufactured your own XSS vulnerability. Always HTML-encode any data you put into HTML. ("data" is anything you want to appear on screen.)

In the HTML DOM this is thankfully completely automatic. Just use the text property, not the HTML property.

var code = [
        '<script type="text/javascript" src="http://source.com/test.js"><\/script>',
        '<script type="text/javascript">',
        '\tadimp.id = ' + 1 + ';',
        '\tadimp.type = ' + 1 + ';',
        '\tadimp.generate();',
        '<\/script>'
    ].join('\n');

$('#code').text(code);
// --------^^^^

Live demo: http://jsfiddle.net/6qdBD/3/


Pre tags format the text not necessarily keep what the text within them from being executed as html. Or in this case JavaScript. A better method would be to replace < and > with the html entities &lt; and &gt;.


Instead of using the < and > symbols use &lt and &gt

var code = '&ltscript type="text/javascript" src="http://source.com/test.js"&gt&lt/script&gt\n'


I suggest to just simply replace the < in <script tag to '&lt and at the end to '&gt.


Since HTML tags are permitted inside PRE, you cannot just "insert" a text file into an HTML document by slapping <PRE> and </PRE> around them. You have to convert the &, < and > characters into entities first.

From http://htmlhelp.com/reference/wilbur/block/pre.html

0

精彩评论

暂无评论...
验证码 换一张
取 消