javascripthtmldom

how to remove <script> from the page before it loads it contents


I have a page hosted on a server which injects small portion of script to my index.html page and would like to remove this script before it runs. Simplified example looks like this

<!doctype html>
<html lang="en">
<body> 
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

I want to prevent the 'console.log("go");' from being executed. I have tried to add a script which removes the removeme script:

<!doctype html>
<html lang="en">
<body>
nothing to show
<script id="script_which_removes_the_other_script">
    // First attempt
    console.log("1 trying to remove " );
    const unwantedScript = document.getElementById('removeme');
    console.log("1 the script tag to remove: " + unwantedScript );
    if (unwantedScript) {
        unwantedScript.remove();
        console.log('1 Unwanted script removed.');
    }
    else{
     console.log('1 Did not found the script to remove.');
    }

    // Second attempt
    document.addEventListener('DOMContentLoaded', () => {
        console.log("2 trying to remove " );
        const unwantedScript = document.getElementById('removeme');
        console.log("2 the script tag to remove: " + unwantedScript );
        if (unwantedScript) {
            unwantedScript.remove();
            console.log('2 Unwanted script removed.');
        }
     });
</script>
<script id="removeme">
    console.log("go");
</script>
</body>
</html>

But neither block 1, neither block 2 cannot stop the method from being run. The console output is as follows:

1 trying to remove 
1 the script tag to remove: null
1 Did not found the script to remove.
go
2 trying to remove 
2 the script tag to remove: [object HTMLScriptElement]
2 Unwanted script removed.

How can I prevent the function from the removeme block from being run?


Solution

  • Try a more aggressive approach by removing the script element immediately as soon as it is created in the DOM.

    Here is my approach, hope help you. Add the following code to the first script tag:

    console.log("Attempting to remove the unwanted script.");
    
    // Observe the document for any changes
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
          if (
            node.nodeType === 1 &&
            node.tagName === "SCRIPT" &&
            node.id === "removeme"
          ) {
            node.remove(); // Remove the unwanted script
            console.log("Unwanted script removed.");
          }
        });
      });
    });
    
    // Start observing the document
    observer.observe(document.body, { childList: true, subtree: true });
    
    // Optionally disconnect the observer after some time or under certain conditions
    setTimeout(() => observer.disconnect(), 5000);