Reputation: 5358
Javascript:
inFrame = true;
try {
if(window.top == self) {
inFrame = false;
}
} catch (err){}
try {
if(window.parent.location == self.location){
inFrame = false;
}
} catch (err){}
This is a piece of javascript code I use to detect whether my library is inside an iframe. 1 out of 100% of requests report that my library is inside an iframe which I think is not possible.
Is there a possibility that this code to fail [report true on false or vice versa]?
From access log [I log every such iframe requests]
Will there be any difference while window
or document
is being loaded in the properties [self, location, top, parent
] I use to check? Because my script loads and executes synchronously mostly before the document is ready or window is completely loaded and that does the iniframe test to proceed further.
Upvotes: 5
Views: 695
Reputation: 708146
If all you're trying to do is detect when your code is in a frame of any kind, all you need is this:
if (window.top !== window) {
// you are embedded in a frame
}
or to set your variable inFrame
like this:
inFrame = (window.top !== window);
or in function form:
function isInFrame() {
return (window.top !== window);
}
As long as you aren't accessing properties on the window.top
object, you shouldn't need exception handlers to protect from cross domain parents. In a cross-origin situation, you can access window.top
, but you cannot access properties such as window.top.location.href
.
As for your other questions:
Is there a possibility that this code to fail [report true on false or vice versa]?
The first part of your code looks OK though the exception handler is not required. The second part of your code will throw an exception every time in modern browsers when the window and parent frame are different origins.
Will there be any difference while window or document is being loaded in the properties [self, location, top, parent] I use to check? Because my script loads and executes synchronously mostly before the document is ready or window is completely loaded and that does the iniframe test to proceed further.
At the point your window is loading, it is safe to make this check. Both window
and window.top
will be valid at that point even if neither has completed loading yet. So, there should not be any issues with inFrame detection that require you to wait for anything to complete loading.
Upvotes: 1
Reputation: 1333
this is how I get the is in frame result and it works for me inFrame = window.top != window
Upvotes: 1
Reputation: 39014
You know most modern browsers allow you to "View Frame" right? As in, view the frame content without the parent. That's an entirely plausable answer for 3. (I do it all the time).
A plausible cause of 1 and 2 is that self
is not really defined in javascript therefore may not always be equal to window
. You should therefore be checking window
or better yet window.self
not self
like Özgür suggests.
Upvotes: 0