javascript 跨域获取iframe当前src url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8766281/
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
Getting iframe current src url in cross domain
提问by Fallouturama
I have an iframe in my web app and I need to get its current url from the parent document (also when the user navigates the frame and change the original source url).
我的网络应用程序中有一个 iframe,我需要从父文档中获取其当前 url(当用户导航框架并更改原始源 url 时也是如此)。
Url is needed simply to social share it.
只需要 URL 就可以进行社交分享。
As a cross-domain scenario, I don't own the child document (its a remote domain).
作为跨域场景,我不拥有子文档(它是一个远程域)。
I am aware of the same-origin-policy that prevents cross domain access from parent document to child one, but I'm looking for a solution by any creative mean possible - there has to be a way around.
我知道防止从父文档到子文档的跨域访问的同源策略,但我正在寻找任何可能的创造性方法的解决方案 - 必须有办法解决。
回答by David Bradshaw
If you don't control the iFrame content, then the only solution is to create a proxy that injects the following line of code into every page.
如果您不控制 iFrame 内容,那么唯一的解决方案是创建一个代理,将以下代码行注入每个页面。
window.postMessage(window.location,'*');
Then on the parent page you can listen for the message.
然后在父页面上,您可以收听消息。
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
console.log(event.data);
}