开发者

Access IFrame's parent URL [duplicate]

开发者 https://www.devze.com 2023-04-09 08:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplic开发者_运维技巧ate: access parent url from iframe
This question already has answers here: Closed 11 years ago.

Possible Duplic开发者_运维技巧ate:

access parent url from iframe

I've been looking around but can't find a set answer or solution for this. I have 2 websites, www2.domain.net and www3.domain.net both these websites have an iFrame on them that links to www.domain.co.uk/iframe.html

What I want to do is check the parent URL, i.e - is the user accessing www2.domain.net or www3.domain.net so I can show specific information to just people accessing www3.domain.net.

Is this possible?

Thanks, Andrew


It's possible, but not very straightforward and requires that you have control over all three pages involved.

If you do control all three sites there's cross window messaging, courtesy of window.postMessage(). However, it's a (relatively) new addition to the DOM and unsupported in older browsers like IE 7, IE 6, Safari 4, Firefox 2 and Opera 9.

// Parent:
iframeWin.postMessage("Hello, from "+window.location.host);


// Iframe: 
window.onmessage = function (evt) { alert(evt.origin); }

Another option is to pass the domain via the URL and then parse this at the other end:

<iframe src="www.domain.co.uk/iframe.html?www2.domain.net" />

and the required JavaScript (called from the page inside the iframe):

alert(window.location.search);
//-> "?www2.domain.net"


It is not. iframes are considered frames and so the cross domain policy applies to them. Since the iframe domain (www.domain.co.uk/iframe.html) is different than the parent domain (www3.domain.net) it cannot access the parent domain. I believe, however, that you can still access the iframe from the parent domain either through the DOM or via window.frames (an array of all frames including iframes).


It is not possible in this case (as posted) due to Same Origin Policy. However, it seems that you control all these domains. If so, you could pass the parent domain in the iFrame tag's src attribute using query string and access it in the iFrame page. See @Andy's answer for implementation.

0

精彩评论

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

关注公众号