zaf
zaf

Reputation: 23244

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('myiframe');
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?

Upvotes: 4

Views: 3265

Answers (1)

Digital Plane
Digital Plane

Reputation: 38264

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);

Upvotes: 3

Related Questions