Detect iFrame embedding in Javascript

I have an application on which there is a specific page - call him Page A. Page A is sometimes a top-level page, but also sometimes embedded as an iframe inside page B. All pages come from the same server and there are no problems between domains.

I have a greasemonkey script that runs on page A. How does a greasemonkey script detect if page A is in an iframe context or not?

+45
javascript greasemonkey iframe
May 29 '09 at 8:47 a.m.
source share
5 answers

Looking at the frame length, it breaks at all if page A itself has frames (I know that this may not be the case for this particular instance). A more reliable and significant test will be:

if (window!=window.top) { /* I'm in a frame! */ } 
+109
May 29 '09 at 9:04 a.m.
source share

Predicate

 (window.parent.frames.length > 0) 

will tell you what you want.

+10
May 29 '09 at 8:51 a.m.
source share
 if (top === self) { not in a frame } else { in a frame } 

From How to determine if a webpage is loading inside an iframe or directly in a browser window?

+4
Aug 22 '11 at 15:54
source share

As stated above, the decision does not work in IE8. In addition, checking window.parent.frames.length may cause cross-domain exclusion.

Instead, I was able to achieve this with var isInIFrame = top.location != self.location - it works in IE8 and does not cause cross-domain violation if you are not trying to read the contents of top.location .

+4
Jul 05 '13 at 14:38
source share

Use window.frameElement and check if it is null and if its nodeName is "IFRAME".

0
Jun 11 2018-12-12T00:
source share



All Articles