From: http://goo.gl/2lY89
Two years ago, I wroteCodeTo prevent web pages from being embedded into a frame ).
<SCRIPT type = "text/JavaScript">
If (window! = Top) // determines whether the current window object is the top object.
Top. Location. href = Window. Location. href; // If not, the top object URL is automatically directed to the URL of the embedded webpage.
</SCRIPT>
This code is valid. However, there is a problem: once used, no one can embed your webpage into the framework, including yourself.
So I am thinking about it today,Is there a way for my webpage to be embedded in my own framework rather than other frameworks?
On the surface, this problem is very simple. You only need to make a judgment: whether the Domain Name of the current framework is the same as that of the top-level framework, and if the answer is the same, a URL redirection is made.
If (top. Location. hostname! = Window. Location. hostname ){
Top. Location. href = Window. Location. href;
}
However, unexpectedly, this write is wrong and cannot be run at all. Can you see where the error is?
Assume that top. Location. hostname is www.111.com, and window. Location. hostname is www.222.com. That is to say, 111.com embeds 222.com into its webpage. In this case, compare top. Location. hostname! = Window. Location. hostname?
The browser will prompt the code error!
Because they are cross-domain, the browser's security policy does not allow 222.com webpages to operate on 111.com webpages, and vice versa. IE calls this error "no permission ". Further, the browser does not even allow you to view the top. Location. hostname. When this object is viewed across domains, an error is reported directly.
So how should I modify the code?
In fact, this prompts us to check whether the top. Location. hostname error is returned. If an error is reported, it indicates that cross-origin exists, and URL redirection is performed on the top object. If no error is reported, it indicates that no cross-origin exists (or no framework is used.
Try {
Top. Location. hostname;
}
Catch (e ){
Top. Location. href = Window. Location. href;
}
This is correct and can be run correctly in IE and Firefox. However, Chrome may encounter errors. For some reason, Chrome does not report errors for top. Location. hostname in cross-origin scenarios!
No way. You can only add additional code for chrome.
Try {
Top. Location. hostname;
If (top. Location. hostname! = Window. Location. hostname ){
Top. Location. href = Window. Location. href;
}
}
Catch (e ){
Top. Location. href = Window. Location. href;
}
Now, the upgraded code is complete. All domain names except the local domain name cannot embed your webpage into the framework. My blog now uses this code.