Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Chrome extension in the background

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>

like image 660
woutr_be Avatar asked Feb 09 '12 07:02

woutr_be


1 Answers

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;
like image 106
sysop Avatar answered Nov 18 '22 03:11

sysop