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?
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.
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});
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:
chrome.runtime.getBackgroundPage
) and handle the results.I've provided the code corresponding to this flow in this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With