开发者

How do you break out of frames without breaking the browser's back button?

A site that links to mine keeps my site in a frame, so I added the following JavaScript to my page:

if (window.top.location != window.location) {
    window.top.location = window.location
}

Now if I get to my site via the offending site, my site successfully breaks out of the frame. But the back button breaks! The back button sends the user to the framed version of my site, which immediately breaks out again, returning him to where he was try开发者_开发知识库ing to leave! Is there a simple way to fix this?


window.top.location.replace(window.location);

The replace method is specifically for this purpose. It replaces the current item in the history state with the new destination so that the back button won't go through the destination you don't want.


jfriend00's answer is indeed correct. Using the window.location.replace method will work without affecting the back button.

However, I'd just like to note that whenever you want to stop a page from being framed, you should do more than just that! There are a couple methods of preventing a simple script like that from breaking out of the frame, which work in many modern browsers. Perhaps you can disable the page, display a message with a link to the full page, something like that. You could also use the X-Frame-Options response header that tells the browser not to display the page in a frame. If you don't take some of these measures, your site could be clickjacked.


Another solution is to open your site in a new window leaving a friendly message in the iframed site:

if (parent.frames.length) 
{ window.open("mySite.htm", "MySite");
  location.href= "framedMessage.htm";   
}

Where framedMessage.htm contains some friendly/warning message.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜