Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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 trying to leave! Is there a simple way to fix this?

like image 621
zjmiller Avatar asked Jul 11 '11 22:07

zjmiller


People also ask

Can I disable browser back button?

You can-not actually disable the browser back button. However, you can do magic using your logic to prevent the user from navigating back which will create an impression like it is disabled.

How do I disable the Back button in Chrome?

Select Settings from the list. Scroll down to the Privacy and Security section, and select the Site settings from the menu. Choose the Pop-ups and redirects option within Site settings. Toggle the button to turn OFF and block the pop-ups and redirection.


3 Answers

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.

like image 188
jfriend00 Avatar answered Sep 18 '22 12:09

jfriend00


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.

like image 22
DSKrepps Avatar answered Sep 21 '22 12:09

DSKrepps


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.

like image 25
Mrchief Avatar answered Sep 20 '22 12:09

Mrchief