8

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?

Don
  • 863
  • 1
  • 8
  • 22
tic
  • 4,009
  • 15
  • 45
  • 86

4 Answers4

6

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

apsillers
  • 112,806
  • 17
  • 235
  • 239
1

It is always best to create the elements and append them, rather than straight inserting any html using innerhtml.

You can use read more about it here: https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet

This fragment works:

var newScript = document.createElement( "script" );
newScript.type = 'text/javascript';
var scriptContent = document.createTextNode( "googletag.cmd.push( function() { googletag.display( '" + encodeURIComponent( divID ) + "' ); } );" ); 
newScript.appendChild( scriptContent ); 

Here is the example in action: https://jsfiddle.net/BrianLayman/4nu667c9/

Brian Layman
  • 456
  • 3
  • 10
0

Actually you can use eval but that's not a good practice for security issues. You can do something like this:

var scr = document.createElement('script');
scr.src = 'yourscriptsource';
document.body.appendChild(scr);

Hope it helps!

axcdnt
  • 14,004
  • 7
  • 26
  • 31
-5

You don't to do that. In Firebug go to the "Console" tab. You can enter code directly there. Next to the three blue angle brackets at the bottom of the console type this and then hit the enter key: alert("asdf");

austincheney
  • 1,189
  • 9
  • 11
  • The OP is trying to diagnose why this line of code does not work as expected. The OP almost certainly *is already* using the Firebug console (where else could (s)he `run the following line in Firebug` other than the console?). – apsillers Jul 27 '12 at 20:46