【问题标题】:How do Chrome extensions update toolbar notifications when extension is closed?扩展程序关闭时,Chrome 扩展程序如何更新工具栏通知?
【发布时间】:2022-07-08 04:42:36
【问题描述】:

Lastpass 和 Traitsniper 等扩展程序如何在扩展程序关闭时更新扩展程序通知计数?即使扩展程序关闭,是否有任何扩展程序正在运行?我目前正在使用带有清单 v3 的 background.js 中的事件来更新它,当扩展程序未打开时它不会运行。 extensions notifications example

Manifest.json:

{
   "short_name": "test",
   "name": "test",
   "version": "1.3",
   "manifest_version": 3,
   "action": {
      "default_popup": "index.html",
      "default_title": "Open the popup"
   },
   "permissions": ["contextMenus", "notifications", "storage", "tabs"],
   "icons": {
      "512": "logo512.png"
   },
   "background": {
      "service_worker": "./static/js/background.js"
   },
   "content_scripts": [
      {
         "matches": ["<all_urls>"],
         "js": ["./static/js/content.js"]
      }
   ],
   "devtools_page": "index.html"
}

来自 background.js 的片段,当前正在更新扩展工具栏中的通知计数:

switch (unreadCount) {
      case 0:
         chrome.action.setBadgeBackgroundColor({
            color: [110, 140, 180, 255],
         })
         chrome.action.setTitle({ title: 'No unread messages' })
         chrome.action.setBadgeText({ text: '' })
         break
      case 1:
         chrome.action.setBadgeBackgroundColor({
            color: '#F00',
         })
         chrome.action.setTitle({
            title: unreadCount + ' unread message',
         })
         chrome.action.setBadgeText({ text: unreadCount.toString() })
         break
      default:
         chrome.action.setBadgeBackgroundColor({
            color: '#F00',
         })
         chrome.action.setTitle({
            title: unreadCount + ' unread messages',
         })
         chrome.action.setBadgeText({ text: unreadCount.toString() })
         break
   }

【问题讨论】:

  • 后台脚本与扩展的UI无关。它在隐藏的背景上下文中单独运行。将您的代码和 manifest.json 添加到问题 (MCVE)。
  • 谢谢@wOxxOm - 我已经更新了我原来的帖子。我错误地认为当扩展程序关闭时后台工作人员能够运行。这就是我面临的主要问题,如何在扩展未打开时运行一些代码。
  • 后台脚本是基于事件的,因此您需要将此代码放置在此类事件的侦听器中。请参阅documentation 了解更多信息。
  • 感谢@wOxxOm - 我在后台脚本中设置了事件,计时器事件工作正常,但是当扩展程序关闭时事件不会触发,并且每次扩展程序打开时简单的计数器都会重置为 0 /关闭。我的主要问题是有事件,或者某种代码一直在运行,即使扩展没有打开。我只是在这里询问 Chrome 扩展的某些核心部分是否可以 100% 运行(即使扩展未处于活动状态)。
  • 定时器不是这样的事件。您可以使用 chrome.alarms API。另见Persistent Service Worker in Chrome Extension

标签: google-chrome google-chrome-extension push-notification alerts lastpass


【解决方案1】:

只是想解决这个问题——这实际上是 Metamasks 的扩展提供程序访问 window.ethereum 的问题。 https://github.com/MetaMask/extension-provider/

警报和徽章文本更新一切正常,即使扩展程序关闭,直到我声明 Metamask 提供程序:

let provider = createMetaMaskProvider()

然后,警报仅在应用打开/可见时起作用。为什么会这样,对我来说有点疯狂,调试时我看不到任何错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2019-12-19
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多