Detect iFrame embedding in Javascript

蹲街弑〆低调 提交于 2019-11-26 02:54:55

问题


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?


回答1:


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! */ }



回答2:


The predicate

(window.parent.frames.length > 0)

will tell you just what you want.




回答3:


if (top === self) { not in a frame } else { in a frame }

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




回答4:


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.




回答5:


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



来源:https://stackoverflow.com/questions/925039/detect-iframe-embedding-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!