子域跨源框架访问被阻止:无法调用iframe内容方法求助
跨域iframe内容访问问题解决方案
问题概述
两个同主域子域 x.domain.com 和 y.domain.com,y.domain.com 嵌入 x.domain.com 的iframe后无法访问其内容,尝试CSP未解决,且无法修改iframe原代码,postMessage方案不可用。
相关代码
x.domain.com/frame.html:
<html> <body> </body> <script> function myFunc() { console.log('called'); } </script> </html>
y.domain.com 调用代码:
let iframe = (iframe_element.contentWindow || iframe_element.contentDocument); if (iframe.document) iframe = iframe.document; iframe.myFunc();
解决方法
由于两个子域同属 domain.com,可通过统一 document.domain 绕过同源策略限制,无需修改iframe原代码:
在y.domain.com页面中设置document.domain
在父页面的脚本开头添加:document.domain = 'domain.com';在x.domain.com服务器端注入document.domain设置脚本
通过服务器配置在返回的HTML中自动插入设置代码,无需修改原frame.html:- Nginx配置:
server { # 已有配置... sub_filter '</head>' '<script>document.domain="domain.com";</script></head>'; sub_filter_once on; } - Apache配置:
先确保启用mod_substitute模块,再添加:AddOutputFilterByType SUBSTITUTE text/html Substitute "s|</head>|<script>document.domain='domain.com';</script></head>|i"
- Nginx配置:
完成配置后,两个页面的 document.domain 统一为主域,同源策略限制解除,即可正常访问iframe内容并调用myFunc函数。
注意:CSP的作用是管控资源加载和脚本执行权限,无法突破同源策略对跨域iframe内容访问的限制,因此之前用CSP尝试解决无效是合理的。
内容的提问来源于stack exchange,提问作者Abdul Sadik Yalcin
相关产品推荐
相关产品推荐

