开发者

How to find out if DOMContentLoaded event comes from iframe or not?

I am working on a Firefox extension and it uses something like this:

function myExt()
{
    this.handleEvent = function (event)
    {
        switch (event.type)
        {
            case "DOMContentLoaded":
            {
                alert('fired');
            }
        }
    }

    window.addEventListener ("DOMContentLoaded", this, false);
}

My problem is that the alert gets executed multiple times if the page contents iframes, so what I am looking to do is, using "event" on this.handleEvent I need to find out if event.target references the top window or the iframe window.

How c开发者_Python百科an I do this?


You could try checking for event.target.frameElement. If it's undefined then it's the main document, but if it is defined then it's a frame. I can't remember if this is only for frames, though, or if it's for iframes too.


Yeah, iframe is weird in that will fire DOMContentLoaded. It treats the content as if it were in its own 'window'. Have you tried getting the event.target's parent or ownerDocument?

I used Firebug on an SVG loaded into an <object> tag and I believe that ownerDocument gets what you're looking for.


I am still doing some tests but it looks like this function does the job:

this.isTopLevel = function(event){
    var doc = event.target;
    for(var i = 0; i < gBrowser.browsers.length; i++) {
        if(gBrowser.browsers[i].contentDocument == doc) return true;
    }
    return false;
};


I'm using this snippet to filter out iframes:

var browser = gBrowser.getBrowserForDocument(event.target);
var pageIsFrame = (event.target instanceof Ci.nsIDOMHTMLDocument &&
  event.target != browser.contentDocument);
if (pageIsFrame) {
  // Not interested in frames.
  return;
}

You need Chrome privileges for that.

In the new add-on SDK content scripts (where you don't have Chrome privileges), I'm using this:

if (window.frameElement) {
  // This is an iframe.
  //...
}

(See MDC doc here or here).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜