开发者

Read parent location from within a frame (different domains)

开发者 https://www.devze.com 2023-02-12 17:02 出处:网络
How could an iframe read its parent location URL, the domains of the parent window and the iframe being different?

How could an iframe read its parent location URL, the domains of the parent window and the iframe being different?

I know that the "common" answer to this question is that because of the domains conflict, browsers don't allow cross-domain accesses. So the following won开发者_开发百科't work:

parent.location.href

But maybe someone could think out of the box here and propose something similar to the Cross-document messaging hack?


Perhaps you could check document.referrer? Of course, that will only work if the user has not yet clicked a link inside the iframe.


I got it!!

My solution is the following:

1. Use the onload attribute with the frame

<iframe src="http://website.com/" onload="src+='#'+document.location"></iframe>

2. Monitor hash changes in the frame

var referrer = '?';
window.onhashchange = function() {
  var ref = document.location.hash;
  if(ref && ref.length > 1) {
    var t = ref.split('#');
    ref = t[1];
  }
  referrer = ref;
};

And "voilà" :-)

By the way, you'll find some more details about the onhashchange event.

0

精彩评论

暂无评论...
验证码 换一张
取 消