0

I would like to pass the tab.id to the callback function for chrome.tabs.sendMessage so that I can use the id and url of the respective tab in another function that I have in the callback.

I know that the callback parameter will be sent by the handler of the message (in my case the contentScript). And I should be able to pass the tab information as a parameter from contentScript, but, this is only possible if the connection was opened from a tab (including content scripts) (reference: docs).

In my case the connection was opened from popup.js. So i'm not able to use the tab.id in the callback.

Below is an example:

// popup.js
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
  chrome.tabs.sendMessage(
    tabs[0].id,
    { from: 'popup', subject: 'testCallback' },
    callbackFunction
  );
});

const callbackFunction= info => {
   console.log(info.tab.id);
   console.log(info.tab.url);
};

Current Solution:

My current solution is to query the tabs again in the callback and get the curret tab from the result like below, but I'm wondering if its possible to use it without the additional query

// popup.js
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {

  chrome.tabs.sendMessage(
    tabs[0].id,
    { from: 'popup', subject: 'testCallback' },
    callbackFunction
  );
});

const callbackFunction = info => {
   chrome.tabs.query({ active: true, currentWindow: true }, function (activeTabs) {
      console.log(activeTabs[0].id);
      console.log(activeTabs[0].url);
   });
};
Gangula
  • 5,193
  • 4
  • 30
  • 59
  • 1
    Just pass the data explicitly: `info => callbackFunction(tabs[0], info)` or use `bind`. – wOxxOm Aug 22 '22 at 19:54
  • @wOxxOm, I was able to pass the data explicitly in manifest v2 in Microsoft Edge, but its not working properly in Firefox. do you know what could be the issue? – Gangula Aug 23 '22 at 13:02

0 Answers0