skip to Main Content

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?

2

Answers


  1. 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);
    
    Login or Signup to reply.
  2. If the <script> tag is injected server-side by searching for the closing </body> tag, then you could just not output it. Both the <html> tag and the <body> tag have optional end tags.

    Another options is to have the browser block the script:

    Browsers include CSP. A Content Security Policy tells the browser what types of content it should execute. You can disable all inline <script> tags and only allow your own <script> elements, either by linking them (<script src="">) or by including a nonce attribute:

    <!DOCTYPE html>
    <meta http-equiv="Content-Security-Policy" 
      content="script-src 'self' https: 'nonce-abc123'">
    
    <body>
    
    Only the first <tt>&lt;script&gt;</tt> element will be executed, 
    the other will trigger an error in the browser console.
    
    <script nonce="abc123">
    console.log(1);
    </script>
    
    <script>
    console.log(2);
    </script>
    

    This particular CSP value will allow <script> tags that come from the same server (/file.js), from https links (https://example.com/file.js) or if they include a nonce property with the value abc123. Note that the single quotes matter.

    If the script you’re trying to block is not inline but includes a src (<script src="">) then you remove either 'self' or https: from the policy (whichever is applicable) and add the nonce attribute to all of your own scripts.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search