Get iframes complete url which is from another domain
The parent page can get the URL (and fragment) of an iframe but after the iframe updates its URL fragment the parent cannot get the updated URL with fragment.
Example iframe URL: http://example.com/a/b/c/d.html?k1=v1#i1=j1 (Note fragment)
This is in a cross domain environment. The parent domain is different to the iframe domain. Currently only testing using firefox.
Using the following code:
var ifr = document.getElementById('myifra开发者_如何转开发me');
if(ifr){
alert(ifr.src);
}
Is it impossible due to security?
I'm trying to get the iframe to communicate with the parent using the fragment as the payload.
Both domains are under my control and I'm trying to avoid the long way to achieve communication between the pages.
Are there any other techniques that don't involve a server round trip?
You can use window.postMessage
API to communicate between frames by calling postMessage
on any window
object. This works for cross-domain messaging, as long as the receiving frame has a message
event listener.
postMessage Usage:
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");
To listen for messages:
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);
精彩评论