【问题标题】:SecurityError: Blocked a frame with origin "ionic://localhost" from accessing a cross-origin frame. Protocols, domains, and ports must matchSecurityError: 阻止了来源为“ionic://localhost”的框架访问跨域框架。协议、域和端口必须匹配
【发布时间】: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


【解决方案1】:

我最终找到了一个插件,可以将 javascript 注入到 iframe 中。

很遗憾,它仅适用于 ios 应用程序。我还没有找到适用于 Android 的类似产品。

它在 github 上:

https://github.com/moodlemobile/cordova-plugin-wkuserscript

【讨论】:

    猜你喜欢
    • 2018-09-10
    • 2020-07-21
    • 2014-09-25
    相关资源
    最近更新 更多