开发者

greasemonkey script try to access element before it exist and gets null

I have 开发者_如何学Csmall script running on "google.com/*" using Greasemonkey

basically my script adds a few menu items to google menu (where you can find Images Videos Maps News Shopping etc ...);

this menu is inside qbar div so its look like:

<div id="gbar"> ...menu code ... </div>

the next line in my script works fine if you go to google webpage (www.google.com):

var gbar = var gbar = document.getElementById("gbar");
if (qbar != null) alert("qbar exist!");
else alert("qbar is null");

this code alert qbar as exist which is good.

now if i look for anyword in google for example search for "madman" will get you to this page:

http://www.google.com/#sclient=psy&hl=en&q=madman&aq=f&aqi=g5&aql=&oq=&pbx=1&fp=fd0f73886609171d

now the script still running only now it alert "gbar is null"

I think the reason is that the script is running before the gbar element get created on the page. which is weird cuz i was sure the grease monkey script runs only when all content finished loading.


You can set up a DOM mutation event. Basically, here are the steps:

  • Do a initial search document.getElementById('gbar') and process it if found.

  • Set up a DOMNodeInserted event handler on the document.

    • If the inserted element has id="gbar" then you know that gbar is inserted.
    • If not, search inside the inserted element for an element with id="gbar" and process it if found.

You can see a working example code. It adds 5 exclaimation marks when a gbar is added to the document.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜