问题
I'm trying to find a reliable solution to determine if my page was loaded in iframe on external site using javascript.
If iframe src located on the same domain it's preaty easy: you can use if (window.frameElement) or if (window.location !== window.parent.location) but if iframe src is not on the same domain all modern browsers throw exception when accessing parent and even comparing it with null.
I'm totally lost.
回答1:
You might be interested in the Coding Horror entry: We Done Been Framed. Offers an interesting technical discussion on this topic, including solutions, and frame-busting-busting.
回答2:
You can wrap your validation (window.location !== window.parent.location / window.frameElement) in try-catch statement which you can use to handle the exception yourself.
回答3:
Why don't you try a function with the following
var element = window.parent.document if (element) return "Is in a parent window" else "is not in a parent window";
来源:https://stackoverflow.com/questions/4179795/how-to-understand-if-page-is-loaded-as-iframe-external-site-using-javascript