Dynamicly set document.domain to iframe

2019-02-17 07:11发布

I have an iframe that injects in pages, called him "helper". So due to same origin policy i need to set iframe domain the same is parent window domain. But i cant get access to parent window domain. How can it be solved?

Update #1

This code is currently work for 2nd level domains:

pathArray = window.location.host.split('.'); var arrLength = pathArray.length; var domainName = pathArray.slice(arrLength - 2, arrLength).join('.'); document.domain = domainName;

but I need to somehow get it from parent window rather than relying on 2nd level domain

4条回答
Summer. ? 凉城
2楼-- · 2019-02-17 07:18

Assuming you parent can be a.domain.com and your iframe is b.domain.com - then you can do what your are attempting. If you MUST know what the parent is, pass it in the iframe src attribute or try document.referrer

查看更多
姐就是有狂的资本
3楼-- · 2019-02-17 07:31

In short, it can't. Setting document.domain only works when the iFrame and containing window are actually part of the same domain. If a browser were to let you set document.domain to something other than the domain you were actually on, it would be a security violation. Consider, any malicious script could just say 'No really, trust me on this one' and the browser would essentially be saying, 'Oh, okay, since you asked so nicely, here's all the permission you want'.

document.domain can only be set to a parent domain of the actual domain of the page. If an iFrame and a containing window don't share at least that, then no browser will allow them to cross talk.

Unless I've misunderstood your question. Feel free to post some examples to clarify.

查看更多
Deceive 欺骗
4楼-- · 2019-02-17 07:34

add document.domain = 'your.domain' in both the pages.

like this. don't forget both parent.top

document.domain = 'corp.local'; only parent like

document.domain = 'corp'; won't work.

As I've mentioned here. javascript get iframe url's current page on subdomain

this document helped. http://javascript.info/tutorial/same-origin-security-policy

查看更多
啃猪蹄的小仙女
5楼-- · 2019-02-17 07:41

I do not know if it will help but i use this in iframe

 try {
            var domainName = window.parent.parent.iframeData.domainName;
        }
        //Access violation
        catch (err) {
            document.domain = window.location.hostname.replace('www.', '');
        }

So i check if domain already set we have exception ang try to guess domain, in either case, there is no need to set a domain

EDIT: More correctly to use post message to set domain if needed

查看更多
登录 后发表回答