Access parent from iframe even though domains don't match?

大城市里の小女人 提交于 2019-12-13 05:57:29

问题


I have a javascript script that is being run from within an iframe that is trying to access the parent but I'm getting the following error:

Unsafe JavaScript attempt to access frame with URL mysite.com from frame with URL myothersite.com?. Domains, protocols and ports must match.

The iframe html is on a different domain but I didn't think that would matter. This is the code that is generating the JS error:

var parent_site = parent.document;

Is there a way around this?


回答1:


If the parent domain is a trailing part of the iframe domain (i.e., iframe is child.parent.com and parent is parent.com) you can set the domain of the iframe document with document.domain = "parent.com" and avoid the problem.

If the domains of the parent and the iframe are unrelated there is no way to work around it.




回答2:


Do some research on CORS (Cross-origin resource sharing): http://www.w3.org/TR/cors/

You essentially need to add this to your .htaccess of the parent domain:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers x-requested-with

Ideally you'd replace the * with the domain(s) for which you want to allow access.



来源:https://stackoverflow.com/questions/12044771/access-parent-from-iframe-even-though-domains-dont-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!