Search code examples
javascripthtmlgoogle-chromebrowsergreasemonkey

About JavaScript: Can I modify the contents of a script tag after the js text contained in it is loaded and before it is executed?


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?


Solution

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