简体   繁体   中英

Running a function every minute in a Google Chrome extension

So I'm trying to make a Google Chrome extension that will run a function every minute and update the icon color. I can't seem to get the script to run even though I've followed multiple tutorials.. Currently here is what I have..

Manifest.json

{
  "manifest_version": 2,

  "name": "Icon changer",
  "description": "changes icon.",
  "version": "1.0",

  "browser_action": {
    "default_icon": "green.png",
    "default_popup": "popup.html",
    "background-page": "checker.html"
  },
  "permissions": [
    "https://google.com/"
  ]
}

checker.html

<!doctype html>
<html>
    <script src="check.js"></script>
    <body onload="startRequest()">
        sample
    </body>
</html>

check.js

function updateBadge() {
    chrome.browserAction.setIcon({path:"red.png"});
}

var pollInterval = 1000 * 60; // 1 minute, in milliseconds
var timerId;

function startRequest() {
    updateBadge();
    timerId = window.setTimeout(startRequest, pollInterval);
}

function stopRequest() {
    window.clearTimeout(timerId);
}

I just want it to change once to know that it works but the icon isn't changing. Once I get it changing I can do what I actually wanted to do.

EDIT: I just tested check.js and it runs fine when the button is clicked, it just doesn't get started by the chacker.html page.

In the chrome extension you are not allowed to insert inline script in html, if I remember correctly.

remove:

<body onload="startRequest()">
        sample
    </body>

and see this js:

(function() {
  var updateBadge = function() {
      chrome.browserAction.setIcon({path:"red.png"});
  }

  var stopRequest = function() {
      window.clearTimeout(timerId);
  } 

  var pollInterval = 1000 * 60; // 1 minute, in milliseconds
  var timerId;

  updateBadge();
  timerId = window.setTimeout(startRequest, pollInterval);

})()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM