Reputation: 1317
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?
Upvotes: 2
Views: 698
Reputation: 3227
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.
iframe
is served from the same port locallyThis 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.
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');
Upvotes: 1