Search code examples
jquerydomgreasemonkeyappendto

Jquery appendTo('body') makes multiple inserts when used with Greasemonkey


I've made an Greasemonkey script which uses jQuery appendTo('body').
Everything is working fine but the HTML is also appended to other DOM elements like Google ads and gadgets on my igoogle page.

Is there something to fix this? I don't think some example code is necessary for this issue. Instead I've uploaded a picture that shows my problem:

my igoogle page


As you can see, my appended HTML shows up in many different places.


Solution

  • Yes, this is caused by the fact that Greasemonkey treats each frame and iframe as its own page (which in a way, it is), and runs as the @include, @exclude, and/or @match directives indicate.
    (Note that iframes without a src attribute are considered to be from the same URL as the base page.)

    To stop a script from triggering on iframes, place this code near the top of your script:

    if (window.top != window.self)  //-- Don't run on frames or iframes.
        return;
    


    If you actually want to run on some iframes and not others, tune the @include, @exclude, and/or @match directives if possible, or link to the target page for help choosing a method to selectively block iframes.