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);
});
};