On many browsers, if I do:
var x = document.createElement("SPAN");
x.innerHTML = "<script>alert(1);</script>";
document.body.appendChild(x);
no alert will happen.
Are there any browsers for which it will happen? If so, which ones?
On many browsers, if I do:
var x = document.createElement("SPAN");
x.innerHTML = "<script>alert(1);</script>";
document.body.appendChild(x);
no alert will happen.
Are there any browsers for which it will happen? If so, which ones?
None. innerHTML doesn't run script elements (unless they have a defer attribute, but I don't think that is universal).
I haven't tested the following, but it should be universally supported among browsers which have DOM and JS support.
var script = "alert(1)";
var script_node = document.createTextNode(script);
var script_element = document.createElement('script');
script_element.type = "text/javascript";
script_element.appendChild(script_node);
document.body.appendChild(script_element);
As David pointed out, using .innerHTML
wouldn't work.
Thought most people would think adding to the DOM is the way to go, this method doesn't work on Safari 2.0.
The best way, the one used in scriptaculous, is to use document.write()
:
// inserting via DOM fails in Safari 2.0, so brute force approach
document.write('<script type="text/javascript">alert("hi");<\/script>');
Adding a script via innerHTML doesn't work in any browsers I know of. Adding a script node via the dom doesn't work in IE. If you've got an html string which includes script tags that you want to insert into the page, your best bet is to extract the script-tag content and eval that. The prototype library has a handy evalScripts function to do exactly this (as well as other functions to insert the html and eval scripts, etc).