1

I am developing a Greasemonkey script to append a div right after the body tag, here is the jQuery:

$("body:first").append (
  '<div id="btn" style="width:50px;display:block">SHOW</div>  <div id="gmPopupContainer" style="display:none">my text here</div>'
);

It works fine as long as there is only one body tag on the page, but a problem arises when there are iframes on the webpage. It appends to all the body nested in the iframes.

I've tried many jQuery selectors without success. What is the correct way to do this?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Yvon Huynh
  • 453
  • 3
  • 16

2 Answers2

3

In general, use @noframesDoc in your metadata block to stop the script from running in iframes.

Or, in this case you can also use something like:

var topmostFramesMainBody = $(top.document.body).first ();

If that doesn't work, provide the details specified in My very simple Greasemonkey script is not running?.
(Note that you should ALWAYS provide those details.)

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295
0

You can do $("<div id="btn" ...>SHOW</div>").insertAfter('body');

Victor Levin
  • 1,167
  • 6
  • 11
  • 1
    it doesn't work either,because it will insert after all body tags found on the web page including those in the iframes, i even tried $('document.body'). I need to refer to the body of the main document and discards all the rest – Yvon Huynh Aug 31 '15 at 21:12
  • OK, give your main body an ID: `...` and then do `$("
    SHOW
    ").insertAfter('body.mainBody');`
    – Victor Levin Sep 01 '15 at 12:30
  • i cannot give an id to the body since i am writing a cross site greasemonkey script so i dont control the web page. – Yvon Huynh Sep 01 '15 at 21:31