我在域上有一个页面:
http://main.mydomain.com/frame.cfm它包含一个 iframe, 加载域名http://www.anotherdomain.com .
本页http://www.anotherdomain.com有一个脚本引用 http://sub.mydomain.com/somescript.js
这个 somescript 是一个类似于 google Analytics 的跟踪脚本,它会随着 www.anotherdomain.com 的每个请求而加载。
在某个阶段,脚本http://sub.mydomain.com/somescript.js在 www.anotherdomain.com 页面中将尝试调用 window.top.aFunction(); or parent.aFunction();
让父窗口执行某些操作。
我了解 X-Frame-Options 和 Access-Control-Allow-Origin header ,并尝试了这两个 header ,但当我在 www.anotherdomain.com 上的 iframe 中浏览时,我在 Firebug 中收到一条错误消息,告诉我:
Error: Permission denied to access property 'relocate'window.top.aFunction();
在 main.domain 站点上的 web.config 中,我有以下规则:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://sub.mydomain.com" />
<add name="X-Frame-Options" value="ALLOW-FROM http://sub.mydomain.com" />
</customHeaders>
</httpProtocol>
我认为这应该授予 sub.mydomain.com 访问 main.mydomain.com 上脚本的权限。
我正在我的电脑上使用除 www.anotherdomain.com 之外的所有域进行测试,并使用适当的主机引用。
知道我在这里缺少什么吗?
最佳答案
您无法通过跨域 iFrame 访问父窗口函数的方法。它违背了 Same Origin Policy 。 X-Frame
http header 响应告诉浏览器是否允许在 iFrame 中渲染页面,并且对您的情况没有帮助。
我推荐的解决方案是使用window.postMessage()
在两个框架之间进行通信。看http://ejohn.org/blog/cross-window-messaging/
关于javascript - 从 Iframe 调用父窗口方法(不同),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13313052/