iplus26
iplus26

Reputation: 2637

How to communicate between popup page and background page and store the info that I already get?

I'm making a google chrome extension to give the specific information (via ajax with server side) for different url (tab).

I use chrome.tabs.onUpdated and chrome.tabs.onActivated event listener in background.js to detect whether the url of the active tab is changed, and then send an ajax request to change the icon using chrome.browserAction.setIcon. (Yes, I would like to use browser action instead of page action because I wanna show some overall information of the extension in popup page, like Adblock Plus does)

However, what I can't figure out is:

  1. How could I communicate between the background and the popup page? I understand that I should use chrome.tabs.sendMessage() and chrome.runtime.onMessage to communicate between background and the content scripts, but how could I communicate between the former and the popup script? I can't see that I need content scripts to modify the content of the page.
  2. How to "store" the information I already get, in the popup page of each page so that I don't need to send few more requests, when the user change the activated tab but the url is not changed?

Any idea? Thanks in advance!

Upvotes: 1

Views: 3582

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

For question #1, since the background page and popup page both live in extension process, they can communicate with each other directly like setting variables or calling functions. You could check the following two posts:

As for question #2,

  1. After learning how to communicate between popup page and background page, you can save the info retrieved from popup page in background page, and remember to set persistent: true in manifest.json, it will ensure the background page lives through the whole extension life.
  2. You can also use chrome.storage or localStorage api to store the data. You can save the data in one page and feel free to access it in another page (So this will be also a way to communicate between two pages to some degree)

Upvotes: 3

Related Questions