views:

144

answers:

3

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?

A: 

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);
David Dorward
A: 

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>');
Sinan Taifour
document.write won't work on page with a complete DOM (which is usually the case once people start thinking about innerHTML) — and the market share of Safari 2 is tiny. It is two versions behind stable on a platform that tends to be upgraded more than Windows systems (which continue to leave us with the legacy of IE6)
David Dorward
A: 

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).

Justin Ludwig