Reputation: 1112
For Chrome Extensions, how can you show the active tab URL in a sidePanel and have it update when it changes?
I found a way to get the initial active tab. But I need it to update when the tab changes.
I tried the suggestion in comments in Chrome Extension - get tab ID in sidePanel? but that didn't work.
I want to be able to use this to enable/disable some buttons in the side panel depending on the URL of the active tab.
I saw this about Enabling the side panel for a specific site (https://developer.chrome.com/docs/extensions/reference/sidePanel/#by-site) but that doesn't actually work. A user would have to manually reopen the side panel. (See https://github.com/GoogleChrome/chrome-extensions-samples/issues/982)
=== Additional info ====
In comments it was suggested I use chrome.tabs.onUpdated. I've tried that unsuccessfully, which is why I'm asking.
I tried this in sidepanel.js
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
console.log("-----", tabId, changeInfo, tab);
});
but if I switch to another tab it doesn't get called. It does get called if I change the URL in the active tab.
Upvotes: 2
Views: 1855
Reputation: 1112
The solution was to use a combination of onActivated and onUpdated. The onActivated will be called when the user changes tabs. The onUpdated is called when a tab URL is changed. Since onUpdated can be called on a no longer active tab (e.g. type the URL for a slow loading site that will change then go to another tab) also check that the tab is active.
Put this code in the sidepanel and create a setActiveURL to handle the URL changes.
/* Set for initial active tab when open the sidepanel */
(async () => {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
setActiveURL(tab.url);
})();
chrome.tabs.onActivated.addListener(async (activeInfo) => {
const tab = await chrome.tabs.get(activeInfo.tabId);
if (tab.active) {
console.log("======= active tab url", tab.url);
setActiveURL(tab.url);
}
});
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (tab.active) {
console.log("======= active tab url", tab.url);
setActiveURL(tab.url);
}
});
Upvotes: 3