1

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?

9
  • Give it an id Commented Nov 23, 2016 at 21:32
  • @StephenThomas How? I don't own the website I am simple editing it, via a userscript. Commented Nov 23, 2016 at 21:33
  • If you know the index to which the <script> is appended (i.e. if it's always added first or last in <head>) you can use its index to remove it from the DOM. Commented Nov 23, 2016 at 21:33
  • @BenM it is the 1st script in a div given the id of "overlay". Do you mind creating the code? I am still learning Commented Nov 23, 2016 at 21:36
  • 1
    document.getElementsByTagName("script") gives you an Array of scripts. Just iterate through it and locate the script using any heuristic. However, mind that deleting a script does not remove the code, functions, etc.. from the Javascript VM if it has already been loaded. Commented Nov 23, 2016 at 21:36

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I have tried implimenting this into my code, but it doesn't work. I also relised that I wrote the <script> outside of the body by accident. I fixed this in the question. Could that have something to do with why it doesn't work?
@grahamcracker1234 No, the code works correctly (i.e. it answers your question about removing the <script> tag from the DOM... You can see it working here: jsfiddle.net/yfbyy1ym/1 The <script> tag is correctly removed from the DOM (inspect the element), but the script has already been sent to the JS engine.
is there a way to direct access it without the index within #overlay ? Some other method?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.