How can I pass values between parent page js and child popup js?

Issue

My parent page js file script:

var PopupConnect = window.open("http://localhost:8080");
var popup_function = PopupConnect.CreateText();

My popup page js file script:

function CreateText() {
  var text = "random text";
  return json({
        result: text
      })
}

This js line in parent page runs fine which triggers a new tab in the browser:

PopupConnect = window.open

The error I am getting is in the line after it:

Uncaught TypeError: PopupConnect.CreateText is not a function

How can I call the js function in child page from the parent page js correctly? Is that even possible? And how can I pass back the result from CreateText function to the parent page js?

NOTE: The parent page is running on Python server & the child popup page is running on Node.js server. Both pages of course are opened in the same browser.

Some people might suggest using localStorage.setItem and localStorage.getItem method but it doesn’t work the two pages are running on different localhost ports and of course in production they will be running on different domains. FYI I have already tried this method and it didn’t work.

UPDATE:

**I ended up using window.postMessage in parent page & have put addEventListener in child popup so once it receives the message it runs the js function. Now the issue I am facing is with timing things.

How can I insert a delay after window.open is called so the child page has time to fully load before parent page runs window.postMessage? I know there is something called ‘await’ but I assume this is for JS being used as backend not frontend? What is the best approach for this timing issue?**

Solution

You can try it with Window.postMessage . hope to help you

Create an event listener in parent page & child page.

Send:
Parent page sends —–message—-> to child page (event listener)
Reply:
Child page sends —–message—-> to parent page (event listener)

Update : about timming new page onload : you can send a message from new page to parent page when ready

Answered By – Xupitan

Answer Checked By – Jay B. (AngularFixing Admin)

Leave a Reply

Your email address will not be published.