TOday I needed to demo DOM Based XSS, and I came across this page which is made for the same exact purpose. I wonder why <img+src+onerror=alert(1)> works but <script>alert(1)</script> does not?

1 Answer 1


The page you refer to has the following code:

<p id="p1">Hello, guest!</p>
var username = searchParams.get('name');
document.getElementById('p1').innerHTML = 'Hello, ' + username + '!';

Your expectation is, that setting username to <script>alert(1)</script> should result in <p id="p1">Hello, <script>alert(1)</script></p> which should in your opinion result in the script getting executed.

But this is not the case. The documentation of Element.innerHTML explains why:

HTML5 specifies that a <script> tag inserted with innerHTML should not execute.

Immediately preceding this statement there is also an example which is similar to yours to illustrate this.

  • This is a... weird... restriction, since (as demonstrated) it is no protection against XSS. At best it might protect against somebody accidentally shooting themselves in the foot, but if they wanted to do that, they should have made innerHTML read-only.
    – CBHacking
    Commented Jul 25, 2018 at 20:11
  • @CBHacking: I don't think that this restriction was actually done for better security but I did not found why it was done either. Maybe existing implementations did this and thus it was specified as the way to go in order to be backward compatible. Commented Jul 25, 2018 at 20:22
  • Interesting restriction, I didn't know about it. Still, I don't see it in the another draft (but I might be blind this morning). By, the note doesn't say "should" but simply "script... do not execute" which means browsers will more likely implement it.
    – Xenos
    Commented Jul 26, 2018 at 7:24
  • 1
    @Xenos: in the current HTML 5.2 standard it still states: "When inserted using the document.write() method, script elements execute (typically blocking further script execution or HTML parsing), but when inserted using innerHTML and outerHTML attributes, they do not execute at all." Commented Jul 26, 2018 at 8:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .