Persistent background page on demand or an event page that doesn't unload?

后端 未结 3 714
温柔的废话
温柔的废话 2020-11-30 10:36

I want to build a extension that behaves like a timer. It should count down the seconds when activated, but should do nothing with inactive.

The chrome.alarms API is

3条回答
  •  眼角桃花
    2020-11-30 11:02

    Background pages cannot be unloaded on demand, and Chrome decides Event page lifecycle for you (there is nothing you can do in onSuspend to prevent it).


    If your concern is timers, you could try my solution from this answer, which basically splits a timer into shorter timers for a "sparse" busy-wait. That's enough to keep the event page loaded and is a viable solution if you don't need to do that frequently.


    In general, there are some things that will keep an event page loaded:

    If you're using message passing, be sure to close unused message ports. The event page will not shut down until all message ports are closed.

    This can be exploited if you have any other context to keep an open Port to, for example a content script. See Long-lived connections docs for more details.


    In practice, if you often or constantly need precise, sub-minute timers, an Event page is a bad solution. Your resource gains from using one might not justify it.

提交回复
热议问题