10

I want to log text on any webpage (using content-script to handle selection) into a database that is popup's resource in order to collect text in one place.

what i am trying I create a database in popup page and try to manage it from content-script though popup is not active (not opened) by using chrome messaging but cannot make the popup receives any message from content-script.

I'm not sure about using messaging to solve this problem. Is there any better solution?

Jing
  • 660
  • 9
  • 23

1 Answers1

26

A content script cannot send a message to an invisible popup, because the popup's context is inactive (closed) when it's hidden.

There are several solutions to your problem.

Option 1: No message passing, use storage events

If your "database" is in fact a simple key-value store, switch to the chrome.storage API. This API is available to the Content script and the popup, and comes with an event to notify you of value changes.

Example:

// Get notified of changes (in the popup?)
chrome.storage.onChanged.addListener(function(changes, areaName) {
    // Do whatever you want with the changes.
});
// Initialization of the popup (print initial information?)
chrome.storage.local.get({keyName: 'defaultValue'}, function(items) {
    // Do something with items.keyName
});

// Content script, storage (remember document title?)
chrome.storage.local.set({keyName: document.title});

Option 2: Pass messages to the background/event page

The popup and the background / event page share the same process. Any database tied to the popup is also available to the background page, and vice versa. A high-level overview of this method:

  1. Content script sends a message to the background page.
  2. The background page stores the value in the database
  3. If the popup is open, update the popup's view.
  4. If the popup is opened (so it was closed before), it should read the database (either directly, or by reading data from the background page using chrome.runtime.getBackgroundPage) and handle the results.

I've provided the code corresponding to this flow in this answer.

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • thanks you :D **option 2** would be ok for me but I still struggle at step **(3)**. I could not get any window object of popup page by calling getViews method from background page. It just returned a window object of itself(background page). – Jing Jun 14 '13 at 16:10
  • @Jing Did you open the popup? If not, then the popup will not show up in `getViews()`, because the view is inactive. That's why step 4 exist (if the popup's view was always visible, then step 3 would always succeed, and step 4 unnecessary). – Rob W Jun 14 '13 at 16:28
  • oh I did not open the popup as you said. finally I used popup' view as the same as background's view and added `chrome.runtime.onMessage.addListener` in a background script. anyway I just know that bg and popup running in the same process, thanks you @Rob W – Jing Jun 14 '13 at 16:51