单击工具栏图标时,Service Worker 不收听操作 - Chrome Extension v3

Service worker not listening to the action when the toolbar icon is clicked - Chrome Extension v3

我是新手。

我有一个要求,点击工具栏图标时应该打开一个新标签。

我的清单文件:

{
  "name": "App",
  "description": "App",
  "version": "1.0",
  "manifest_version": 3,
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  },
  "commands": {
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y"
      }
    }
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {},
  "web_accessible_resources": [
    {
      "resources": ["static/*"],
      "matches": ["<all_urls>"]
    }
  ],
"permissions": ["activeTab", "tabs", "background"],
  "content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'"
  }
}

还有我的 background.js 文件

chrome.action.onClicked.addListener(function (tab) {
  chrome.tabs.create({
    url: chrome.runtime.getURL("index.html"),
    active: true,
  });
});

此代码当前仅打开一个新选项卡一次,之后服务工作者将变为非活动状态。重新加载扩展后,只有我可以打开新选项卡。有解决办法吗?

似乎这个 Chrome 错误影响了您:

Issue 1316588: browserAction not getting dispatched when extension button clicked

我可以通过降级到清单版本 2 来解决这个问题。

我的 manifest.json 文件:

{
  "name": "App",
  "description": "App",
  "version": "1.0",
  "manifest_version": 2,
  "icons": {
    "16": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  },
  "commands": {
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+Y"
      }
    }
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {},
  "web_accessible_resources": ["static/*"],
  "permissions": ["https://*/*", "http://*/*"],
  "content_security_policy": "script-src 'self'; object-src 'self'"
}

我的 background.js 文件如下所示:

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.create({
    url: chrome.extension.getURL("index.html"),
    selected: true,
  });
});

我参考了 daily.dev 的 source code 并修复了错误。