drdaeman
drdaeman

Reputation: 11471

Communicating with a content script on active tab from a Chrome extension's page action popup

I'm not getting how to pass data between content script and page action popup.

I've started with the following simple skeleton, that shows an page action for any page having a minus-dash in title:

Now, in a page action's popup, I want to show matched page's title. Not the last loaded page's title (as would be done by using this answer), but the title of the active tab.

My first though was to send a query to the content script, but according to documentation chrome.extension.sendMessage will send it to all listeners (i.e. all my content scripts on all tabs), without any clear definition on whose response I'll receive back. Also, I can't use chrome.tabs.sendMessage as it requires tabId. Trying to find the current tab using chrome.tabs.getCurrent will return null, as the query comes from non-tab context (from a popup).

I guess I could probably use chrome.tabs.executeScript to communicate, but this just feels dirty.

Still, I believe, this is a basic thing that should be very simple to do and I'm just missing something. Could someone, please, help me, preferably, with an example code?

Update: I've found Mappy example extension and it uses chrome.tabs.onUpdated to keep track of the active tab. This, unfortunately, requires tabs permission. Personally, I'd like to use least privileges possible.

So, is it just unfortunately bad permission system design and I have no choice but to do it this way, or there's any workaround? I'd be happy if chrome.pageAction.onClicked event handler (which provides Tab object that I need) would allow me to show a popup...

Upvotes: 2

Views: 3584

Answers (2)

Sudarshan
Sudarshan

Reputation: 18534

There are multiple Problems in your code

  • chrome.extension.sendRequest in chrome.extension.sendRequest({"what": "match", "title": title}); is deprecated
  • chrome.pageAction.onClicked will not fire when you have "page_action": {"default_popup": "popup.html", …}, in your manifest.
  • chrome.extension.sendMessage will send it to all listeners (i.e. all my content scripts on all tabs), is an invalid assumption, it will send to Extension Pages.

I tried to read your question multiple times but couldn't understand what is you want to achieve, could you explain it?

Upvotes: 1

Uzair Farooq
Uzair Farooq

Reputation: 2427

I think you need to add the onClick event listener in your popup:

chrome.pageAction.onClicked.addListener(function(tabs.Tab tab) {...});

See documentation here.

Callback of the event listener would provide you the tabId which would surely be the active tab.

Upvotes: 1

Related Questions