Home > Back-end >  About JavaScript: Can I modify the contents of a script tag after the js text contained in it is loa
About JavaScript: Can I modify the contents of a script tag after the js text contained in it is loa

Time:09-17

For example, I have a <script> alert(1) <script> in the web page. Now what I want to do is to change it to <script> alert (2) <script> after it is loaded and before it is executed, immediately. Can I succeed?

CodePudding user response:

The short answer is no; only by modifying the page before it is served

As you can see, you cannot intercept the script with script

It will be executed when parsed

window.addEventListener("DOMContentLoaded",function() {
  document.scripts[1].textContent = "";
  alert(2)
})
<script>alert(1)</script>

Here is a hack

window.addEventListener("DOMContentLoaded",function() {
  alert(3)
})
<script>// if you can insert this before you can intercept alert
const saveAlert = window.alert;
window.alert = function(str) {
  saveAlert(2)
  window.alert = saveAlert;
};
</script>
<script>alert(1)</script>

Proof that the other answer does not work

var h = document.getElementById('hello');
h.textContent = 'alert(2)'
<script type='text/javascript' id='hello'>
    alert(1)
</script>

CodePudding user response:

Say you set your script tag like so

<script type='text/javascript' id='hello'>
    alert(1)
</script>

Then you can get the dom element like so:

var h = document.getElementById('hello');

You can then modify the element like so:

h.innerHTML = 'alert(2)'

I would suggest also that you use something like JQuery onready to make sure that the modification code executes before the alert in the script tags.

  • Related