在后台运行Chrome扩展程序 [英] Run Chrome extension in the background

查看:123
本文介绍了在后台运行Chrome扩展程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在创建我的第一个Chrome扩展程序,这非常好。
这只是一个测试,我运行多个计时器。



但是,显然,当我打开和关闭扩展程序时,所有计时器都会重置。



因此,为了保持所有定时器的运行,当我关闭扩展并使它们在后台页面中运行时,我必须以某种方式使它们相同。



如何处理这个问题?



我已经有了所有定时器的数组,对我来说最好的选择是什么>

解决方案

当启用分机时,后台页面始终运行。您看不到它,但它可以修改扩展的其他方面,例如设置浏览器动作标志。



例如,以下操作会将图标徽章设置为数字假设服务中的未读项:

  function getUnreadItems(callback){
$ .ajax(...,函数(数据){
进程(数据);
回调(数据);
});


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

$ / code>

然后,您可以提出请求并安排它,以便检索数据并您可以随时停止请求。

  var pollInterval = 1000 * 60; // 1分钟

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

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

现在只需加载它...

  onload ='startRequest()'






此外,HTML5离线存储可以很好地存储数据并不断更新数据...

  var data =blah; 
localStorage.myTextData = data;


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>

解决方案

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;

这篇关于在后台运行Chrome扩展程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆