If I run the following line in Firebug on any page:
document.documentElement.innerHTML="<script>alert(1)</script>";
why isn't the alert
command executed?
HTML specifies that a <script> tag inserted with innerHTML should not execute. For that reason, it is recommended that instead of innerHTML you use: Element.SetHTML() to sanitize the text before it is inserted into the DOM.
Setting the innerHTML property of an element To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
It looks like that your <script>
tag is being added as you expect, but the code within it is not being executed. The same failure happens if you try using document.head
(or any other DOM element, it seems). For whatever reason (possibly standards compliance, possible security), inline code inside of <script>
blocks that are added via .innerHTML
simply doesn't run.
However, I do have working code that produces similar functionality:
var script = document.createElement('script');
script[(script.innerText===undefined?"textContent":"innerText")] = 'alert(1);';
document.documentElement.appendChild(script);
Here, you add the <script>
block with documentElement.appendChild
and use textContent
or innerText
to set the content of the <script>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With