且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Chrome扩展程序setTimeout无法正常工作

更新时间:2023-12-05 18:55:22

我怀疑这个问题可能会在事件页面处于不活动状态后自动暂停。在我的机器上, onSuspend 似乎在约10秒后调用。



https://developer.chrome。 com / extensions / event_pages#lifetime 注意到


一旦事件页面在短时间内(几秒钟) ,将调度
runtime.onSuspend事件。事件页面在被强制卸载之前还有几个b $ b秒的时间来处理这个事件。


所以,你实际上已经卸载了13秒左右的时间(给你一些onSuspend的清理时间,我估计)。然后你的页面被卸载,并且从那里启动的代码不再运行。



https://developer.chrome.com/extensions/event_pages#transition 说要使用报警api 为事件页面而不是 setTimeout


My first post here =].

I'm building a chrome extension and I'm using a setTimeout recursively. I noticed that if I set it to up to 13secs, it works, but if I set it to 14secs+ it won't work.

This is an example which is on my background.js

function start() {

    var timeout = setTimeout( function() { start(); }, 1000*15);
    alert('test');
}

chrome.webNavigation.onCompleted.addListener(function(o) {

    start();

    }, {
      url: [
        {urlContains: 'http://www.example.com/in.php'},
        {urlContains: 'http://www.example.com/out.php'}
      ]
    }
);

If you reduce that timeout to 1000*13, it works.

This is my manifest.json

{
  "name": "Extension",
  "version": "0.0.7",
  "manifest_version": 2,
  "description": "Keeps proxy session alive",
  "homepage_url": "http://www.example.com",
  "icons": {
    "16": "icons/icon16-on.png",
    "48": "icons/icon48-on.png",
    "128": "icons/icon128-on.png"
  },
  "default_locale": "en",
  "background": {
    "scripts": [
      "src/bg/background.js"
    ],
    "persistent": false
  },
  "browser_action": {
    "default_icon": "icons/icon19.png",
    "default_title": "Example - Off",
    "default_popup": ""
  },
 "permissions": [
    "webNavigation", 
    "*://*/*",
    "https://*/*"
  ]
}

Any idea on what could be causing this oddness? I'm testing this on developer mode, BTW.

Thanks in advance!

EDIT

Code fixed:

manifest.json

I added "alarms" to the permissions

background.js

Added this event to listen to the alarms.create:

chrome.alarms.onAlarm.addListener(function(alarm){
    start();
});

Replaced the setTimeout function with the below line

chrome.alarms.create("Start", {periodInMinutes:1});

Hope this helps!

I suspect the problem may with the automatic suspension of event pages after some period of inactivity. On my machine, onSuspend seems to called after ~10 seconds.

https://developer.chrome.com/extensions/event_pages#lifetime notes that

Once the event page has been idle a short time (a few seconds), the runtime.onSuspend event is dispatched. The event page has a few more seconds to handle this event before it is forcibly unloaded.

So, that may get you more around 13 seconds before the page is actually unloaded (giving you some cleanup time in onSuspend, I reckon). Then your page is unloaded and code initiated from there is no longer run.

https://developer.chrome.com/extensions/event_pages#transition says to use the alarms api for event pages instead of setTimeout.