开发者

Document is used being other tabs

In my firefox addon. I have two tabs open in my browser, when I try to access the "document" after a interval/timeout, in one of the tabs, I grab the document of another tab instead...

For example: Tab 1, document.title is: "Test page" Tab 2, document.title is: "Second tab"

I run a script in tab 1: setTimeout(function(){alert(document.title)}, 5000). Should alert "Test Page", but the alert shows "Second tab".

Here my script:

gBrowser.addEventListener("DOMContentLoaded",function(开发者_如何学Goe){ 
    window = e.originalTarget.defaultView;
    document = window.document;
    setTimeout(function(){ alert(document.title); }, 5000);
}, true);

This only happends when I open the first tab, then a open the second.

The same thing happens when I try to change any dom element.

Also happend when a user click on a button.

How to avoid that? This could be a bug with firefox or is with me?


Don't forget to declare local variables:

gBrowser.addEventListener("DOMContentLoaded",function(e){ 
    var window = e.originalTarget.defaultView;
    var document = window.document;
    setTimeout(function(){ alert(document.title); }, 5000);
}, true);

Undeclared variables are automatically global and in particular can change between now and when your timeout runs (never mind lots of other nasty side-effects).

Even better: switch on strict mode. It will make sure that this mistake produces a visible error and doesn't go unnoticed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜