I have a page with one button. When clicked, that button navigates to http://google.com/
$("#button").click(function(){
window.location="http://google.com";
});
I would like this navigation to work when this page is embedded within the iframe. I don’t want to affect the outside host page, but rather only the contents of the iframe. What’s a good cross-platform way to:
- Detect if I’m contained in an iframe
- If not, navigate like above.
- If yes, navigate the iframe only?
(I’m going to try to implement the algorithm I just described, but regardless I think this question is interesting enough to be posted. If I succeed, I’ll post my solution)
navigate like above
When you write
window.location.href = 'http://www.google.com';you are navigating the contents of the iframe, not that of the top page. If you want to navigate the top page, you can only do this if this top page is on the same domain as the iframe and you could usewindow.top.location.href.UPDATE:
There is a security mechanism built in browsers which forbid you from redirecting to sites that set the
X-Frame-Options: SAMEORIGINresponse header when inside an iframe. That’s the case withhttp://www.google.com. Simply navigate to this site and look at the response HTTP headers with FireBug or developer toolbar you are using and you will see this header. You cannot redirect to it and you will get the following error message:It’s basically a security mechanism implemented by some sites whose authors didn’t want you to embed them in an iframe.