获取来自另一个域的iframes完整url

Get iframes complete url which is from another domain

本文关键字:iframes 完整 url 另一个 获取      更新时间:2023-09-26

父页面可以获得iframe的URL(和fragment),但是在iframe更新了它的URL fragment后,父页面不能通过fragment获得更新后的URL。

示例iframe URL:http://example.com/a/b/c/d.html?k1=v1#i1=j1(注释片段)

这是在跨域环境中。父域与iframe域不同。目前只使用firefox进行测试。

使用以下代码:

var ifr = document.getElementById('myiframe');
if(ifr){
   alert(ifr.src);
}

由于安全原因是不可能的吗?

我试图让iframe与使用片段作为有效载荷的父通信。

这两个域都在我的控制之下,我试图避免在页面之间实现通信的漫长道路。

有没有其他不涉及服务器往返的技术?

您可以使用window.postMessage API通过在任何window对象上调用postMessage来在帧之间进行通信。这适用于跨域消息传递,只要接收帧具有message事件侦听器。

postMessage用法:

otherWindow.postMessage(message, targetOrigin);
//e.g.
yourIFrame.contentWindow.postMessage({curURL: location.href}, "http://www.your2ndDomain.com");
//or
top.postMessage({curURL: location.href}, "http://www.your1stDomain.com");

监听消息:

window.addEventListener("message", function(e){
  //You must check your origin!
  if(event.origin !== "http://www.your1stDomain.com")
    return;
  //Get the data
  var data = event.data;
  alert(data.curURL);
}, false);