Run Chrome extension in the background

2020-05-21 04:41发布

问题:

I'm currently creating my first Chrome extension, so far so good. It's just a little test where I run multiple timers.

But obviously all my timers reset when I open and close the extension.

So to keep all my timers running, I would have to same them somehow when I close the extension and make them run in the background page.

When I open the extension again, those timers should be send back to the open page.

How would you handle this?

I already have an array of all my timers, what would be the best option for me>

回答1:

A background page runs at all times when the extension is enabled. You cannot see it, but it can modify other aspects of the extension, like setting the browser action badge.

For example, the following would set the icon badge to the number of unread items in a hypothetical service:

function getUnreadItems(callback) {
  $.ajax(..., function(data) {
     process(data);
     callback(data);
  });
}

function updateBadge() {
  getUnreadItems(function(data) {
     chrome.browserAction.setBadgeText({text:data.unreadItems});
  });
}

Then, you can make a request and schedule it so the data is retrieved and processed regularly, you can also stop the request at any time.

var pollInterval = 1000 * 60; // 1 minute

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

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

Now just load it...

onload='startRequest()'

Also, HTML5 offline storage is good for storing data and constantly update it...

var data = "blah";
localStorage.myTextData = data;