Search code examples
javascriptgoogle-chrome-extensionchrome-extension-manifest-v3browser-action

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


I am new to this.

I have a requirement, which should open a new tab when clicked on the toolbar icon.

My manifest file :

{
  "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'"
  }
}

And my background.js file

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

This code currently opens a new tab only one time, and after that the service worker becomes inactive. After reloading the extension only I can open the new tab. Is there a solution for this?


Solution

  • I am able to fix this by downgrading to manifest version 2.

    My manifest.json file :

    {
      "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'"
    }
    

    And my background.js file looks like this :

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

    I referred to daily.dev's source code and fixed the bug.