Open and transfer data to a popup window (new tab) from the contents of the script

I am writing a chrome extension and ask a question.

My extension has some kind of .html page, let it be "popup.html". I paste the contents of the script into some page, and this script opens "popup.html" in a new tab with something like "var p = window.open (chrome.extension.getURL ('/ popup.html"), " popup "), which works great. Then I need to transfer some data to this window, and I cannot figure out how to do this in a simple way.

For some reason, I cannot call the child window function from the contents of the script with

var p = window.open(chrome.extension.getURL('/popup.html'), "popup"); p.foo(data); 

In the console, I see Uncaught TypeError: I can not call the 'foo' method of an undefined message.

I cannot pass data in the query string because the data is just too big.

Is there an elegant and easy way to transfer data to such a window? I was thinking about messaging, but how to efficiently get the tab id of a recently opened window using a background page?

Thank you very much in advance.

UPD: I tried to invert the logic and get the data from the parent window using "window.opener.foo ()", but null returned in the newly opened window.opener tab.

+4
source share
1 answer

Well, I found two solutions to my problem.

1) Add a background image that opens a popup with chrome.tabs.create() . Then send a message from the contents of the script to the background image, which forwards it to the appropriate tab through chrome.tabs.sendMessage() . It looks a little ugly but works.

2) Better without a background page. An extension page (popup) creates a listener for a long-term connection. The contents of the script then sends a message to this connection. The problem is that the listener is not created immediately after the page is opened, so there must be a mechanism for the contents of the script to wait for the popup to load. This can be a simple setTimeout or a notification from a popup window over the same long-lived connection.

If anyone has a better solution, I would also love to test it.

+4
source

All Articles