问题描述
我正在尝试访问 ionic 移动应用程序中的 iframe 以设置身份验证 cookie,但在我尝试访问其内容时总是遇到跨域错误。
我需要帮助的是如何获取对 iframe 内容的引用,以便我可以在子页面中设置 cookie。
父页面和 iframe 页面都归我们所有,因此不存在实际的安全问题。问题在于父页面的来源是 ionic://localhost(因为它是一个 ionic 应用),而 iframe 的来源是 https://oursite.com。
我尝试添加:
<allow-navigation href="ionic://localhost/*" />
<allow-navigation href="https://oursite.com" />
<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事件,log显示frame对象,但是访问frame.contentwindow后立即出现cross origin错误,因此无法执行postMessage。
是否有任何解决方法可以访问 iframe 内容或将消息从父窗口发布到 iframe 窗口而不会触发跨源错误?
解决方法
我最终找到了一个插件,可以将 javascript 注入到 iframe 中。
不幸的是,它仅适用于 ios 应用程序。我还没有找到类似的适用于 Android 的。
它在 github 上: