如何为chrome上的每个标签获取不同的徽章值?

时间:2015-08-23 15:42:36

标签: javascript jquery google-chrome dom google-chrome-extension


我尝试做像adblock这样的事情。 Adblock计算"广告的数量"并更新徽章价值。目前,我尝试使用'后台页面进行操作,但它们只运行一次,所有标签的徽章值都相同。我无法使用浏览器操作popup.html,因为它仅在点击后触发。
所以我需要一些获取当前选项卡,能够读取选项卡的当前DOM以及所有更新徽章值之后的内容。但是,在我点击不同的标签后,我需要计算新的徽章价值。
提前致谢

3 个答案:

答案 0 :(得分:12)

如果您指定了tabId参数,则会为每个选项卡单独存储徽章文本,如果您已设置了值,则无需在用户切换选项卡后手动更新徽章文本。

因此,如果您的扩展程序在加载后立即处理页面,请拨打chrome.browserAction.setBadgeText一次。你可以这样做,例如通过从您的内容脚本向您的后台/活动页面发送消息,该页面将使用发件人选项卡的ID调用setBadgeText(此参数使文本对选项卡唯一)。

可能有一个问题:预渲染(尚未显示)标签无法分配徽章文字,因此您必须推迟更新,这是使用tabs和{{3的示例API:

内容脚本:

chrome.runtime.sendMessage({badgeText: "123"});

背景/事件脚本:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.badgeText) {
        chrome.tabs.get(sender.tab.id, function(tab) {
            if (chrome.runtime.lastError) {
                return; // the prerendered tab has been nuked, happens in omnibox search
            }
            if (tab.index >= 0) { // tab is visible
                chrome.browserAction.setBadgeText({tabId:tab.id, text:message.badgeText});
            } else { // prerendered tab, invisible yet, happens quite rarely
                var tabId = sender.tab.id, text = message.badgeText;
                chrome.webNavigation.onCommitted.addListener(function update(details) {
                    if (details.tabId == tabId) {
                        chrome.browserAction.setBadgeText({tabId: tabId, text: text});
                        chrome.webNavigation.onCommitted.removeListener(update);
                    }
                });
            }
        });
    }
});

答案 1 :(得分:1)

您可以在后台/活动页面中收听Chrome tab events。以下代码帮助我解决了同样的问题:

// 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
}

答案 2 :(得分:0)

您可以编写“ onActiveChanged”侦听器,并调用updateBadge函数并传递tabId。希望能有所帮助。

9c0eRtxsdU02fo9.wc3VtsA2FI.gS6a