Can't use postMessage in react components

Viewed 1955

I am trying to open a popup window and pass a message there from a react component, the window opens(http://localhost:3001) but the message is not shown. Here is the code to open popup and postMessage to the popup window:

  React.useEffect(() => {
    document.addEventListener("message", function(event) {
      console.log('event data', event.data, event.source);
    })
  }, []);

  const onAdd = () => {
    const popup = window.open('http://localhost:3001/auth', 'authWindow','height=500,width=500');
    popup.postMessage('data', 'http://localhost:3001');
  }

on that popup window(http://localhost:3001/) open I want to pass a message to my parent window(http://localhost:3000/), here is the code for passing message to parent:

  const receiveMessage = (e) => {
    console.log("message event",  e.data);

    e.source.postMessage("message: asasdas", 'http://localhost:3000')
    // if (event.origin !== "http://localhost:3000")
    //   return;
  }

  React.useEffect(() => {
    window.addEventListener("message", receiveMessage);
  }, [])

But this is also giving an error: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3000') does not match the recipient window's origin ('http://localhost:3001').

1 Answers

Use BroadcastChannel API. I use it in my projects and find it to be more reliable. I don't see the issues that you encountered.

Broadcast Channel

Related