Search code examples
javascripthtmluserscripts

How to delete a script in an HTML Page


So I am making a userscript for a website, which deletes ads. The website added a script which detects, if the ads have been taken out of the HTML. So to fix this again I want to delete the whole script, but it has no identifiers, so I have no clue how to go about it. Say I have this code:

<html>

<body>
    <script>
        if(hasAds) {
            document.write("blah blah blah"); // Act as if this re-ads the ad onto the page
        }
    </script>
    <div id="adsBottom">IMAGINE AD CODE HERE</div>
</body>
     </html>

How could I access the script section and delete it?


Solution

  • Well, since you can presuppose its location in the DOM (and index within #overlay), it's relatively straightforward to remove it using getElementById(), removeChild() and childNodes:

    var target = document.getElementById('overlay');
    target.removeChild( target.childNodes[0] );
    

    Given the following markup:

    <div id="overlay">
        <script>/* AD PREVENTION SCRIPT */</script>
        <p>Blah</p>
    </div>
    

    The above will work (although does rely on the <script> being the first child of #overlay).