I'm trying to do something like adblock does. Adblock counts number of "ads" and update badge value. For now, I tried to do something with 'background pages', but they are run only one time and badge value is the same for all tabs. I can't use browser action popup.html, because it triggers only after the click.
So I need something which takes current tab, is able to read current DOM of tab and after all update badge value. But also after I click on different tab I need to compute new badge value.
Thanks in advance
Note: You can't make new tabs; you can only show or hide existing ones. Scroll to the bottom, then click Save Changes.
To unpin a tab, right-click the tab and select Unpin. To move a tab to a different window, right-click on the tab and point to Move tab to another window. Then select the window you want to move it to. Make sure you're signed in to Chrome with the same profile in both windows.
The badge text is stored for each tab independently provided you specify tabId parameter, you don't have to update it manually after the user switches tabs if you already have set the value.
So if your extension processes the pages immediately after loading, call chrome.browserAction.setBadgeText
once. You can do it e.g. by sending a message from your content script to your background/event page which will invoke setBadgeText
with the sender tab's id (this parameter is what makes the text unique to a tab).
content script:
chrome.runtime.sendMessage({badgeText: "123"});
background/event script:
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.badgeText != null) {
chrome.browserAction.setBadgeText({
tabId: sender.tab.id,
text: message.badgeText,
}, () => chrome.runtime.lastError); // ignore errors due to closed/prerendered tabs
}
});
You can listen to the Chrome tab events in your background/event page. The following code helped me to solve the same problem:
// fires when tab is updated
chrome.tabs.onUpdated.addListener(updateBadge);
// fires when active tab changes
chrome.tabs.onActivated.addListener(updateBadge);
function updateBadge() {
// get active tab on current window
chrome.tabs.query({active: true, currentWindow: true}, function(arrayOfTabs) {
// the return value is an array
var activeTab = arrayOfTabs[0];
if (!activeTab) return;
// compute number for badge for current tab's url
var count = getCount(activeTab.url);
chrome.browserAction.setBadgeText({
text: count.toString()
});
});
}
function getCount(currentUrl) {
// your logic, e.g., return 42
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With