5

I'm writing a chrome extension and have a question.

My extension has some .html page in it, let it be 'popup.html'. I inject a content script into some page and this script opens a 'popup.html' in a new tab with something like 'var p = window.open(chrome.extension.getURL('/popup.html'), "popup")', which works perfectly. Next, I need to pass some data to this window and I can't figure how to do it in a simple way.

For some reason I can't call child window's function from a content script with

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

In the console I see Uncaught TypeError: Cannot call method 'foo' of undefined message.

I can't pass data in a query string, because the data is simply too big.

Is there an elegant and simple way to pass data to such kind of window? I thought about messaging, but how do I effectively get tab ID of a newly opened window w/out using a background page?

Thanks a lot in advance.

UPD: I tried to inverse the logic and get a data from parent window with 'window.opener.foo()' but in a newly opened tab window.opener returns null.

Dmitriy
  • 1,852
  • 4
  • 15
  • 33
  • 1
    I think the more correct title for this question should be "Open and pass data to a new tab". `popup` is a specific term in Chrome Extensions which doesn't seem to be what you're using. – ripper234 Nov 23 '12 at 00:53

1 Answers1

4

Ok, I found two solutions to my problem.

1) Add a background page, which opens a popup with chrome.tabs.create(). Then send a message from a content script to a background page, which re-sends it to a corresponding tab via chrome.tabs.sendMessage(). It looks a little ugly, but works.

2) A better one, w/out background page. Extension (popup) page creates a listener for long-lived connection. Then content script sends a message to this connection. A problem here is that a listener is not created right after the page is opened, so there should be a mechanism for a content script to wait until popup is loaded. It can be a simple setTimeout or a notification from popup via same long-lived connection.

If anyone has a better solution I'd gladly check it out as well.

Dmitriy
  • 1,852
  • 4
  • 15
  • 33
  • Your first solution seems to be the accepted one. See this answer: http://stackoverflow.com/questions/20019958/chrome-extension-how-to-send-data-from-content-script-to-popup-html – Chase Roberts Oct 17 '14 at 15:26