I have a page with one button. When clicked, that button navigates to /
$("#button").click(function(){
window.location="";
});
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)
I have a page with one button. When clicked, that button navigates to http://google./
$("#button").click(function(){
window.location="http://google.";
});
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)
Share Improve this question edited Dec 27, 2011 at 9:32 Purag 17.1k4 gold badges56 silver badges78 bronze badges asked Dec 27, 2011 at 9:27 ripper234ripper234 230k280 gold badges646 silver badges914 bronze badges1 Answer
Reset to default 71) Detect if I'm contained in an iframe
if (window != window.top) {
// the page is inside an iframe
}
2) If not, navigate like above.
navigate like above
3) If yes, navigate the iframe only?
When you write window.location.href = 'http://www.google.';
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 use window.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: SAMEORIGIN
response header when inside an iframe. That's the case with http://www.google.
. 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:
Refused to display document because display forbidden by X-Frame-Options.
It's basically a security mechanism implemented by some sites whose authors didn't want you to embed them in an iframe.