【问题标题】:How can I get different badge value for every tab on chrome?如何为 chrome 上的每个选项卡获取不同的徽章值?
【发布时间】:2015-11-17 01:24:58
【问题描述】:


我正在尝试做类似 adblock 的事情。 Adblock 计算“广告”的数量并更新徽章值。目前,我尝试使用“背景页面”做一些事情,但它们只运行一次,并且所有选项卡的徽章值都相同。我不能使用浏览器操作 popup.html,因为它仅在单击后触发。
所以我需要获取当前选项卡,能够读取当前选项卡的 DOM 并在所有更新后更新徽章值的东西。但在我点击不同的选项卡后,我还需要计算新的徽章值。
提前致谢

【问题讨论】:

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


【解决方案1】:

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

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

内容脚本:

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

背景/事件脚本:

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

【讨论】:

  • 您确定为每个标签存储了徽章文本吗?不是根据我的经验
  • Provided 你指定tabId 参数。我在答案中添加了更明显的说明。
  • chrome.tabs.get 不只是得到你已经拥有的sender.tab 吗?我怎样才能重现“prerendered tab”的情况?
  • 是的,关键是确认标签存在并且可见。无论如何 get() 在 Chrome 67+ 中不再需要,因为他们向 browserAction 方法添加了回调,请参阅更新的答案。
【解决方案2】:

您可以在后台/活动页面中收听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
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-09-25
      • 2017-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多