禁用Chrome浏览器扩展程序的徽章。

8
我正在开发一个Chrome扩展,用于显示通知。我使用以下函数显示通知:chrome.browserAction.setBadgeBackgroundColor和chrome.browserAction.setBadgeText。以下是通知的效果图:
在用户看到通知后,我想要移除这个徽章。我已经试过将其设置为透明,但结果不尽如人意:
有没有人能够帮助我解决如何移除徽章的问题,或者是否还有其他方法可以达到我的目的?
解决方案:当徽章文本为空时,徽章会消失。
3个回答

10

如需删除徽章计数,请将文本设置为空字符串:

chrome.browserAction.setBadgeText({
    'text': '' //an empty string displays nothing!
});

如何移除徽章颜色?!! - moutaz samir
1
它会随着一个空字符串而消失。 - Zig Mandel
2
chrome.browserAction.setBadgeText({ 'text': numUnread || '' }); - Nathan MacInnes
1
@NathanMacInnes,请注意,如果setBadgeText传递的不是字符串(如整数)作为“text”的参数,则会抛出异常。 - Impirator

1

如果您为特定选项卡设置了徽章,请注意取消该选项卡的文本:

chrome.tab.query({currentWindow: true, active: true}, function(tabs) {
    var tab = tabs[0];
    chrome.browserAction.setBadgeText({
        text: ''
        tabId: theTabId
    });
});

0

如果你在2022年遇到这个问题,请使用action而不是browserAction:

chrome.action.setBadgeText({text: ""});

如API文档中所示

如果您也想知道在哪里调用函数以在打开弹出窗口时触发徽章文本消失,只需将其放在您的popup.js(或任何您内容脚本的名称)中即可。

如果您希望在删除徽章文本时在后台脚本中触发一些额外的逻辑,则可以通过您的popup.js发送消息。

  chrome.runtime.sendMessage("clearBadge", (response) => console.log("Badge 
    cleared"));

并且在你的 backgroundworker.js 文件中

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if(message === "clearBadge"){
    chrome.action.setBadgeText({text: ""});
    //do something else
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接