Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent execution of a specific inline script tag

I'm trying to write a script for Tampermonkey that prevents the execution of a specific inline script tag. The body of the page looks something like this

<body>
  <!-- the following script tag should be executed-->
  <script type="text/javascript">
    alert("I'm executed as normal")
  </script>
  <!-- the following script tag should NOT be executed-->
  <script type="text/javascript">
    alert("I should not be executed")
  </script>
  <!-- the following script tag should be executed-->
  <script type="text/javascript">
    alert("I'm executed as normal, too")
  </script>
</body>

I tried to remove the script tag using my Tampermonkey script, but if I run it at document-start or document-body the script tag does not exist yet. If I run it at document-end or document-idle the script tag I'd like to remove is run before my Tampermonkey script is executed.

How can I prevent execution of the script tag?


Note: The actual script tag that I'd like to prevent from executing contains window.location = 'redirect-url'. So it would also be sufficient to prevent the reload in this case.


Versions:

  • Chromium 65.0.3325.181
  • Tampermonkey 4.5
like image 418
maiermic Avatar asked Apr 25 '18 11:04

maiermic


1 Answers

Delete script tag on document-start (as suggested by wOxxOm):

(function() {
    'use strict';
    window.stop();
    const xhr = new XMLHttpRequest();
    xhr.open('GET', window.location.href);
    xhr.onload = () => {
        var html = xhr.responseText
        .replace(/<script\b[\s\S]*?<\/script>/g, s => {
            // check if script tag should be replaced/deleted
            if (s.includes('window.location')) {
                return '';
            } else {
                return s;
            }
        });
        document.open();
        document.write(html);
        document.close();
    };
    xhr.send();
})();
like image 5
maiermic Avatar answered Oct 20 '22 08:10

maiermic