【发布时间】:2021-06-09 02:21:22
【问题描述】:
我正在尝试访问 ionic 移动应用程序中的 iframe 以设置身份验证 cookie,但当我尝试访问其内容时总是遇到跨源错误。
我需要帮助的是如何获取对 iframe 内容的引用,以便我可以在子页面中设置 cookie。
父页面和 iframe 页面均归我们所有,因此不存在实际的安全问题。问题在于父页面的来源是ionic://localhost(因为它是一个离子应用程序),而iframe的来源是https://oursite.com。
我已经尝试添加:
<allow-navigation href="ionic://localhost/*" />
<allow-navigation href="https://oursite.com" />
到 config.xml 并添加:
<script>
let frame = document.getElementById('iframe') as HTMLIFrameElement;
frame.contentWindow.postMessage(this.cookies, '*');
</script>
在父窗口中:
<iframe id="iframe" (load)="onLoad();" [src]="url">
<script>
window.addEventListener('message', event => {
console.log('addEventListener - event.data 1 = ', event.data);
document.cookie = event.data;
if (event.origin.startsWith('ionic://localhost')) {
console.log('addEventListener - event.data 2 = ', event.data);
} else {
console.log('addEventListener - not localhost');
return;
}
});
</script>
</iframe>
在 iframe 中,但这些都不起作用。
当我输入时:
let frame = document.getElementById('iframe') as HTMLIFrameElement;
console.log('aft postMessage, frame = ', frame);
frame.contentWindow.postMessage(this.cookies, '*');
进入iframe onload事件,日志显示frame对象,但是访问frame.contentWindow后立即出现cross origin错误,所以无法执行postMessage。
是否有任何解决方法可以访问 iframe 内容或从父级向 iframe 窗口发布消息而不会触发跨源错误?
【问题讨论】:
-
您好,您找到解决方法了吗?
标签: javascript iframe ionic4 cross-origin-read-blocking