Javascript 获取 parent.location.url - iframe - 从孩子到父母
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4413414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get parent.location.url - iframe - from child to parent
提问by Carlos Castillo
I got a page that is displayed within an iframe.
我有一个显示在 iframe 中的页面。
I need to get the parent.location.url with js from that page (child page).
我需要从该页面(子页面)获取带有 js 的 parent.location.url。
Both sites are in different domains.
两个站点都在不同的域中。
I'm trying:
我想:
alert(parent.location.url)
警报(parent.location.url)
But I get this error:
但我收到此错误:
Permission denied for http://parentdomainto get property Location.URL from http://childdomain.
http://parentdomain从http://childdomain获取属性 Location.URL 的权限被拒绝。
???? Is it possible?
???是否可以?
回答by GianFS
try this:
尝试这个:
var referrer = document.referrer;
alert(referrer);
回答by Madison Williams
What you're trying to do isn't possible per se. Unless you have control over the parent page's calling of the child page. If you do, then you can call the child page with a get statement in the URL of the parent page. So if you parent page is http://parentpage.comthen here's how you should call the iFrame.
你想要做的事情本身是不可能的。除非您可以控制父页面对子页面的调用。如果这样做,则可以在父页面的 URL 中使用 get 语句调用子页面。因此,如果您的父页面是http://parentpage.com,那么您应该如何调用 iFrame。
<iframe src='http://childpage.com/?parent=http://parentpage.com' />
Then all you have to do in the child page to get the reference is get the string with
然后在子页面中获取引用所需要做的就是获取字符串
window.location.search //not sure of browser compatibility with this
and extract the parent page's URL by grabbing it out of that string. I'd give more details, but I'm not even sure about the first question I had.
并通过从该字符串中抓取父页面的 URL 来提取它。我会提供更多细节,但我什至不确定我的第一个问题。
回答by PriorityMark
Have you tried something like:
您是否尝试过类似的事情:
alert(window.top.location.href);
回答by JCOC611
It will onlywork if the parent page and the iframe are on the same domain. If they are not on the same domain you can try passing the location through the src, like Madison Williams suggested.
仅当父页面和 iframe 位于同一域中时,它才有效。如果它们不在同一个域中,您可以尝试通过src传递位置,就像麦迪逊威廉姆斯建议的那样。
That is probably why you are getting "Permission denied..."
这可能就是您收到“权限被拒绝...”的原因
回答by Rob
You'll be able to find it like this, and all browsers should be able to support it:
您将能够像这样找到它,并且所有浏览器都应该能够支持它:
query = window.parent.location.search.substring(1);
You shouldn't get permission errors with this, but I may be wrong.
你不应该得到权限错误,但我可能是错的。
回答by bigmac
Use postMessageto pass data back and forth between the windows. It's a little klunky, but required when having windows communicate across origins.
使用postMessage在窗口之间来回传递数据。这有点笨拙,但在 Windows 跨源通信时需要。
回答by Supratim
Try:
尝试:
var pathname = window.parent.location.href