javascriptfrontendbackendpostmessage

How to use window.postMessage to send data from backend to frontend?


I want to send data I got from backend to frontend by window.postMessage (this image code below) But I received this error: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://127.0.0.1:5173') does not match the recipient window's origin ('http://localhost:8000'). How can I fix it? Please help me

enter image description here

I have tried using window.opener.postMessage but I still receive other error: Cannot read properties of null (reading 'postMessage')


Solution

  • Generally you would use an HTTP client to pass requests and responses between the client and server. Authorization tokens should be encoded and passed in the headers object where they can be received and decoded on either end.

    If you need to pass data in the manner you are describing, you would need to call postMessage on the backend and create an eventListener to accept the message on the client side. Which might look something like this:

    // Frontend
    
    window.addEventListener("message", (event) => {
      if(event.origin !== "http://127.0.0.1:5173"){
        console.log("Invalid Origin")
      } else {
        console.log(event.data)
      }
    }, false);
    
    
    // Server
    
    const popup = window.open();
    popup.postMessage({token}, "http://localhost:8000");