简体   繁体   中英

How can I navigate to another page, from an iframe?

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:

  1. Detect if I'm contained in an iframe
  2. If not, navigate like above.
  3. 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)

1) 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.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 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.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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM