0

<script>
  document.querySelector( 'html' ).innerHTML += 'hello';
</script>

<script>
  document.querySelector( 'script' ).innerHTML += 'alert( "world?" )';
</script>

The alert() function does not fire on page load. This is an overly simplified example but the desired result is to inject additional JavaScript code into a script tag after the page has loaded.

How can this code be altered so that the alert function properly fires in the browser?

Lynel Hudson
  • 2,335
  • 1
  • 18
  • 34

2 Answers2

0

If you have jQuery, you can just use:

$(document).ready(function() {
    $.getScript("http://jact.atdmt.com/jaction/JavaScriptTest");
});

In plain javascript, you can load a script dynamically at any time like this:

var tag = document.createElement("script");
tag.src = "http://jact.atdmt.com/jaction/JavaScriptTest";
document.getElementsByTagName("head")[0].appendChild(tag);
lightningmce
  • 1
  • 1
  • 3
  • Thanks. But is it possible to write to an existing script tag using only vanilla JS? I'm asking this question solely to know the capabilities and limits of JavaScript itself. Also why doesn't my specific example work? – Lynel Hudson Dec 07 '20 at 02:43
  • That's not adding JavaScript to an existing script element, it's creating a new script element and adding it to the document. – lightningmce Dec 07 '20 at 02:45
  • The reason why your example does not work: you can find possible reasons here. https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – lightningmce Dec 07 '20 at 02:48
0

This won't work because the HTML spec doesn't allow for scripts inserted using innerHTML to be executed.

script elements inserted using innerHTML do not execute when they are inserted.

What you can instead do is use the document.createTextNode() method to insert your script body.

<script>
    document.querySelector( 'html' ).innerHTML += 'hello';
    const scriptTag = document.createElement("script");
    const scriptNode = document.createTextNode("alert('Hello World!');");
    scriptTag.appendChild(scriptNode);
    document.body.appendChild(scriptTag);
</script>
Abir Taheer
  • 2,502
  • 3
  • 12
  • 34