Detect iFrame embedding in Javascript

JavascriptIframeGreasemonkey

Javascript Problem Overview


I have an application that has a certain page -- let's call it Page A. Page A is sometimes a top-level page, but also sometimes is embedded as an iframe within page B. All pages come from the same server and there are no cross-domain issues.

I have a greasemonkey script that runs on page A. How can the greasemonkey script detect whether page A is within the iframe context or not?

Javascript Solutions


Solution 1 - Javascript

Looking at frame length breaks down generally if page A itself has frames (I know this might not be the case for this specific instance). The more reliable and meaningful test would be:

if (window!=window.top) { /* I'm in a frame! */ }

Solution 2 - Javascript

The predicate

(window.parent.frames.length > 0)

will tell you just what you want.

Solution 3 - Javascript

Solution 4 - Javascript

As stated above the accepted solution doesn't work in IE8. Additionally, checking window.parent.frames.length can cause a cross-domain exception.

Instead I was able to achieve this with var isInIFrame = top.location != self.location - it works in IE8 and it doesn't cause a cross-domain violation as long as you don't attempt to read the contents of top.location.

Solution 5 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCheekysoftView Question on Stackoverflow
Solution 1 - JavascriptannakataView Answer on Stackoverflow
Solution 2 - JavascriptArtem BargerView Answer on Stackoverflow
Solution 3 - JavascriptMike GraceView Answer on Stackoverflow
Solution 4 - JavascriptzachberryView Answer on Stackoverflow
Solution 5 - JavascriptPink DuckView Answer on Stackoverflow