Get current URL from IFRAME

2018-12-31 14:39发布

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.

3条回答
人气声优
2楼-- · 2018-12-31 14:54

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.

查看更多
残风、尘缘若梦
3楼-- · 2018-12-31 15:09

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.

查看更多
余欢
4楼-- · 2018-12-31 15:15

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!

查看更多
登录 后发表回答