Orion31 Orion31 - 23 days ago 7
Javascript Question

Userscript in inner #document elements

I am trying to write a Tampermonkey script appends HTML to the body, but for some reason, the HTML dialog appears in ads. Google Chrome's inspect element shows this:

#document
<!doctype html>
<html>
<body> <!-- Another Body Tag -->
...
</body>
</html>


As you can see, there is another body tag, so the dialog appears in it, too.
Is there a way to only target the main
<body>
tag, and not those inside a
#document
tag?

Answer

What is likely happening is that because your @match is quite greedy, it runs on all HTML documents on a page. If you only want to run it on the root page, you can check if the window is the "top" window.

if (window !== window.top) { // not the root, return early
    return;
}

This may present a problem when run on pages that are framesets, but that is not a very common practice any more, so I would be surprised if you would find that to be a problem.

Comments