setInteval在后台脚本中 [英] setInteval in background script

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

问题描述

我正在为实时产品开发浏览器扩展.我有一个在manifest.json中设置了"persistent:true"的背景页面(我正在使用v2版本).我使用setInterval()每秒不断地在服务器上轮询新数据.后台脚本还会缓存它收集到的数据,直到显示出来,并将其提供给任何新打开的选项卡.

I am developing a browser extension for a real-time product. I have a background page with "persistent : true" set in the manifest.json (I am using version v2). I am continually polling the server for new data every second using setInterval(). The background script also caches the data it has gathered till present and gives it to any newly opened tab.

一切正常,直到有时我注意到当我将计算机长时间睡眠后,对服务器的轮询才停止!如果刷新了任何现有标签,则确实会看到缓存的数据.这意味着背景页面并未被Chrome杀死.我的问题是,为什么chrome只是停止setInterval()调用?另外,如果由于某种原因而停止轮询,恢复该轮询的正确方法是什么?

Things work fine until sometimes I noticed that when I put the computer to sleep for a long period, my poll to server just stops! If I refreshed any of the existing tabs, I do see cached data. This means, that the background page was not killed by Chrome. My question is, why is chrome just stopping the setInterval() call? Also, what is the correct way to revive the poll if it's stopped for some reason?

//relevant part of manifest.json
  "background": {
    "scripts": [
      "js/background/jquery.min.js",
      "js/background/bgconfig.js",
      "js/background/backgroundmanager.js",
      "js/background/eventsfetcher.js"
    ],

    "persistent": true
  },

谢谢!

推荐答案

对于其他寻求解决方案的人,我最终实现了@Pluto的建议:

For anyone else looking for the solution, I ended up implementing what @Pluto suggested :

"Store the intervalID returned from setInterval in a global variable, then when the window gains focus again, clear that interval and run setInterval again"

到目前为止,这对我来说效果很好,服务器没有发生掉线事件.

This has worked well for me so far with no dropped events from server.

这篇关于setInteval在后台脚本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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