How can I get different badge value for every tab on chrome?

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

61 thoughts on “How can I get different badge value for every tab on chrome?”

  1. 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
    // fires when active tab changes
    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);
          text: count.toString()
    function getCount(currentUrl) {
      // your logic, e.g., return 42
  2. 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) {
          text: message.badgeText,
        }, () => chrome.runtime.lastError); // ignore errors due to closed/prerendered tabs
  3. You can write an “onActiveChanged” listener and call your updateBadge function and pass the tabId. Hope it helped.

    chrome.tabs.onActiveChanged.addListener(function (tabId, changeInfo, tab) {
    function updateBadge(tabId) {

Leave a Comment