Background.js not working Chrome Extension

2020-02-09 12:07发布

I'm new to chrome extensions and cannot seem to figure out how the background concept works. I am building a counter extension that keeps counting even when the user closes the extension (but not the browser) and wanted to do a simple test to see if I could figure out how to use the background file. Below is my attempt to create a function that activates everytime a user clicks on a tab (outside of my extension) and when they click on 5 tabs, the alert hits. I cannot figure out why this doesn't work.

background.js:

var counter = 0;
chrome.browserAction.onClicked.addListener(function(tab){
  counter++;
  if (counter == 5) {
    alert("Hi");
  }
});

manifest.json:

 {
  "name": "Hello World!",
  "description": "My first packaged app.",
  "version": "0.1",
  "permissions": ["tabs", "http://*/*"],
  "manifest_version":2,
  "content_scripts": [ {
    "js": [ "jquery-1.9.1.js", "myscript.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
  "background": {
    "scripts": [
       "background.js"
    ]
  },
  "browser_action": {
    "default_title": "10,000 Hours",
    "default_icon": "icon16.png",
    "default_popup": "index.html"
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  }
}

1条回答
家丑人穷心不美
2楼-- · 2020-02-09 12:37

It is working for me with following code.

manifest.json

{
    "name": "Popping Alert",
    "description": "http://stackoverflow.com/questions/15194198/background-js-not-working-chrome-extension",
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "version": "1",
    "manifest_version": 2,
    "browser_action": {
        "default_title": "Click Me"
    }
}

background.js

var counter = 0;
chrome.browserAction.onClicked.addListener(function (tab) {
    counter++;
    if (counter == 5) {
        alert("Hey !!! You have clicked five times");
    }
});

Can you share your related code or put your problem statement clearly if this does not work?

查看更多
登录 后发表回答