SecurityError: Blocked a frame with origin “ionic://localhost” from accessing a cross-origin frame. Protocols, domains, and ports must match

I’m trying to access an iframe in an ionic mobile app in order to set an authentication cookie, but I’m always getting a cross origin error when I try to access its content.

What I need help with is how to get a reference to the content of the iframe, so I can set the cookie in the sub page.

Both the parent and the iframe pages are owned by us, so there’s no actual security issue. The problem lies in that the parent page has the origin ionic://localhost (because it’s an ionic app) and the iframe has the origin of https://oursite.com.

I’ve tried adding:

<allow-navigation href="ionic://localhost/*" />
<allow-navigation href="https://oursite.com" />

to config.xml and adding:

<script>
    let frame = document.getElementById('iframe') as HTMLIFrameElement;
    frame.contentWindow.postMessage(this.cookies, '*');
</script>

in the parent window and:

<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>

in the iframe, but none of these work.

When I put:

    let frame = document.getElementById('iframe') as HTMLIFrameElement;
    console.log('aft postMessage, frame = ', frame);
    frame.contentWindow.postMessage(this.cookies, '*');

into the iframe onload event, the log shows the frame object, but the cross origin error appears immediately after frame.contentWindow is accessed, so the postMessage cannot be executed.

Is there any workaround to be able to access the iframe content or post a message from the parent to the iframe window without triggering a cross origin error?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.