Get current URL from IFRAME

2018-12-31 14:57发布

问题:

Is there a simple way to get the current URL from an iframe?

The viewer would going through multiple sites. I\'m guessing I would be using something in javascript.

回答1:

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById(\"iframe_id\").contentWindow.location.href

If the two domains are mismatched, you\'ll run into cross site reference scripting security restrictions.

See also answers to a similar question.



回答2:

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you\'ve got the main url!



回答3:

Hope this will help some how in your case, I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe. So in parent window you can:

localStorage.setItem(\"url\", myUrl);

And in code where iframe source is just get this data from localstorage:

localStorage.getItem(\'url\');

Saved me a lot of time. As far as i can see the only condition is access to the parent page code. Hope this will help someone.