How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

前端 未结 16 2333
攒了一身酷
攒了一身酷 2020-11-22 00:28

I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I

16条回答
  •  你的背包
    2020-11-22 00:42

    The accepted answer didn't work for me inside the content script of a Firefox 6.0 Extension (Addon-SDK 1.0): Firefox executes the content script in each: the top-level window and in all iframes.

    Inside the content script I get the following results:

     (window !== window.top) : false 
     (window.self !== window.top) : true
    

    The strange thing about this output is that it's always the same regardless whether the code is run inside an iframe or the top-level window.

    On the other hand Google Chrome seems to execute my content script only once within the top-level window, so the above wouldn't work at all.

    What finally worked for me in a content script in both browsers is this:

     console.log(window.frames.length + ':' + parent.frames.length);
    

    Without iframes this prints 0:0, in a top-level window containing one frame it prints 1:1, and in the only iframe of a document it prints 0:1.

    This allows my extension to determine in both browsers if there are any iframes present, and additionally in Firefox if it is run inside one of the iframes.

提交回复
热议问题