简体   繁体   中英

javascript postMessage using iframe creating errors in react app

I'm getting two errors when running the following code in my React application:

try {
      iframe.src = applicationRoutes.href;
      iframe.style.width = '0px';
      iframe.style.height = '0px';
      iframe.style.border = '0px';
      iframe.style.display = 'none';
      iframe.id = 'iframe';
      iframeRef.current.appendChild(iframe);

      const myIframe = window.frames['iframe'].contentWindow;
      myIframe.postMessage('user info', applicationRoutes.href);
    } catch (error) {
      console.log(error);
    }

The errors I receive are the following:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:4001').

and

Refused to display 'http://localhost:3000/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

What can I do to fix these issues?

Both errors are a result of the iframe and main document being on different ports of your localhost.

Let's break up the message so it's easier to read.

Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided ('http://localhost:3000')
does not match
the recipient window's origin ('http://localhost:4001').

Browsers limit to what degree pages from one origin can access resources from another, this is called CORS (Cross Origin Resource Sharing). An origin is not only defined by its domain name, but also its port number.

Your resource will need to be either from the same origin, or should have an HTTP header on the response that allows cross domain use. So you have 2 options.

Ensure your iframe is served from the same port locally

This could be a sensible solution if the app you're developing will, on production, also always runs on the same domain.

Perhaps you're running 2 instances of a server while really you could run 1 that serves both types?

If that's not possible, you'll have to do the following.

Add a CORS header to the iframe's response

You can add a CORS header with * for simplicity, or a specific host, to tell the browser it's OK to include this on other domains.

For example, in PHP:

 <?php
 header('Access-Control-Allow-Origin: *');

or

 <?php
 header('Access-Control-Allow-Origin: http://localhost:4001');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM