Home > database >  chrome extensension background.js events don't run
chrome extensension background.js events don't run

Time:11-05

I am trying to create a basic chrome extension that opens a new tab when user clicks on the extension. It seems like it doesn't work. When I open extension (click on it), nothing happens (the new tab or window doesn't open).

1.) I created a new project by command yarn create vite chrome-sf-poc --template react

2.) This is the script for generating bundle yarn build && cp src/manifest.json dist/ && public/background.js dist/

manifest.json

{
  "manifest_version": 3,
  "name": "DEV Articles",
  "description": "A quick way to browse top posts from DEV Community.",
  "version": "0.0.1",
  "action": {
    "default_popup": "index.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting", "tabs", "runtime"]
}

background.js

chrome.browserAction.onClicked.addListener(function (tab) {
  chrome.tabs.create({
    url: chrome.extension.getURL("https://www.google.com/"),
    selected: true,
  });

  chrome.tabs.create({
    url: chrome.extension.getURL("https://www.google.com/"),
    selected: true,
  });
});

chrome.runtime.onStartup.addListener(function () {
  chrome.tabs.create({
    url: chrome.extension.getURL("https://www.google.com/"),
    selected: true,
  });

  chrome.tabs.create({
    url: chrome.extension.getURL("https://www.google.com/"),
    selected: true,
  });
});

When I load the extension into chrome, it says that service worker is inactive:

enter image description here

CodePudding user response:

manifest.json looks ok.

{
        "manifest_version": 3,
        "name": "DEV Articles",
        "description": "A quick way to browse top posts from DEV Community.",
        "version": "0.0.1",
        "action": {
          "default_popup": "index.html"
        },
        "background": {
          "service_worker": "background.js"
        },
        "permissions": ["storage", "activeTab", "scripting", "tabs", "runtime"]
    }

Please check background.js

browser.browserAction.onClicked.addListener(function (tab) {
  browser.tabs.create({ url: "https://www.google.com/" });
});

browser.runtime.onStartup.addListener(function () {
  browser.tabs.create({ url: "https://www.google.com/" });
});

CodePudding user response:

I think the script outputs V2. You are trying to migrate it to V3 and failing. I fixed it.

manifest.json

{
  "manifest_version": 3,
  "name": "DEV Articles",
  "description": "A quick way to browse top posts from DEV Community.",
  "version": "0.0.1",
  "action": {
    "default_title": "hoge"
  },
  "background": {
    "service_worker": "background.js"
  }
}

background.js

chrome.action.onClicked.addListener(function (tab) {
  chrome.tabs.create({ url: "https://www.google.com/" });
});

chrome.runtime.onStartup.addListener(function () {
  chrome.tabs.create({ url: "https://www.google.com/" });
});
  • Related