Using setInterval in service-worker

174 views
Skip to first unread message

Adnan Khan

unread,
May 14, 2024, 7:25:57 AMMay 14
to Chromium Extensions
I'm a bit confused and want to get some opinions on this.

Current use-case

Right now, I am checking if all of the tabs are minimized or not. So suppose if all of the tabs are minimized then I need to wait maybe 15 or 30 minutes to execute a certain event. For this, I'm using setTimeout. 

I read documentation regarding how service-worker isn't persistent and it will die but I'm wondering if this is the case yet?

How I can achieve my usecase which is "Execute certain function, after all the tabs are minimized but wait for some interval". In which I am waiting 15 minutes after all the tabs are minimized.

Thanks

Oliver Dunk

unread,
May 14, 2024, 8:03:24 AMMay 14
to Adnan Khan, Chromium Extensions
Hi Adnan,

Have you seen the chrome.alarms API? That would be the suggested way to wake your service worker after a given period of time.

The service worker is already non-persistent. There are things that extend the lifetime, so it may be awake after your interval, but there's certainly no guarantee.
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB


--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/cf4228a6-73dc-4baf-8102-c307d21a627an%40chromium.org.

Adnan Khan

unread,
May 14, 2024, 8:33:40 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
Hi, Thanks for reply.

I really want to go in depth to understand this. Thing is that I'm detecting if all of the tabs are minimized, if it is, then it will start a setTimeout of 30 minutes and it worked fine which now takes me to the question "Why" because all documentation is saying that max active time for any service-worker is 5 minutes.

Now, I tested this on my production extension from webstore to clear out doubt that I am using load unpacked version but it still worked.

Do you have any insights into this that would be really helpful.

Also, I am not keen to use alarm API because it is going to add extra permission.

My use case is simple, if all tabs are minimized - wait 30 minutes atleast to confirm that user isn't doing anything on tabs and then execute certain function.

Thanks alot

Oliver Dunk

unread,
May 14, 2024, 8:43:15 AMMay 14
to Adnan Khan, Chromium Extensions
Is your extension live on the store or would you be comfortable sharing your code? That would be the best way to figure out what is happening.

There are a number of things that can keep the service worker alive: https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/lifecycle#idle-shutdown. Could you be meeting one of those conditions? Regularly calling an API, for example if you had a chrome.tabs.query loop, would be a clear one.

Another cause could be that DevTools is open - this keeps the service worker alive.

Also, I am not keen to use alarm API because it is going to add extra permission.

It does require an additional permission, but there isn't an associated warning. You can add it without users needing to accept anything on update and it won't present a new message on install.
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Adnan Khan

unread,
May 14, 2024, 8:54:27 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
Thanks for reply

I read that doc too but couldn't find reference.
Right now I am using these APIs

1- chrome.windows.onFocusChanged.addListener(windowId => { 2- chrome.idle.onStateChanged.addListener((newState: string) => { 3- chrome.idle.setDetectionInterval(// 30 minutes); 4- chrome.tabs.onRemoved.addListener(async (tabId: any, removeInfo: any) => {
I'm suspecting is it because I registered above events and that keeps the service worker alive? But I couldn't find any such documentation for that and lifecycle of service-worker do not mention it either.

Adnan Khan

unread,
May 14, 2024, 8:56:13 AMMay 14
to Chromium Extensions, Adnan Khan, Oliver Dunk, Chromium Extensions
Sorry for additional reply but I forgot to add that I had no service-worker opened at that time because I ran web-store version by installing it.

Oliver Dunk

unread,
May 14, 2024, 8:56:32 AMMay 14
to Adnan Khan, Chromium Extensions
Within those 30 minutes, are you doing things that change window focus or remove tabs?

Any of those events firing would extend the service worker lifetime by another 30 seconds.
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Adnan Khan

unread,
May 14, 2024, 9:00:57 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
The 30 minutes is in this function by the way.
chrome.windows.onFocusChanged.addListener(windowId => {
Here is full code
    chrome.windows.getAll({populate: true}, windows => {
        if (windowId === chrome.windows.WINDOW_ID_NONE) {
            chrome.tabs.query({active: true, currentWindow: true}, tabs => {
                if (tabs.length === 0) {
                    console.log('Storing timeout in backgroundSyncTimeout variable');
                    ServiceWorkerGlobals.backgroundSyncTimeout = setTimeout(() => {
                        console.log('All tabs are inactive or minimized');
                        backgroundInitiation();
                    }, // 30 minutes);
                }
            });
        } else {
            chrome.tabs.query({}, tabs => {
                const anyActive = tabs.some(tab => tab.active);
                if (anyActive) {
                    console.log('All tabs are back in focus');
                }
            });
        }
    });
});

Adnan Khan

unread,
May 14, 2024, 9:02:52 AMMay 14
to Chromium Extensions, Adnan Khan, Oliver Dunk, Chromium Extensions
Also to mention that   chrome.idle.setDetectionInterval(// 30 minutes); will run the   chrome.idle.onStateChanged.addListener((newState: string) => {  function but it shouldn't keep service-worker alive right?

Oliver Dunk

unread,
May 14, 2024, 9:13:31 AMMay 14
to Adnan Khan, Chromium Extensions
Hmm, there isn't anything in your code snippet that I would expect to keep the service worker alive.

When chrome.idle.onStateChanged runs, it'll wake the service worker, but that should only happen when the state changes and shouldn't impact things long term.

Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Adnan Khan

unread,
May 14, 2024, 9:24:54 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
Thanks for reply,

I'm also using Supabase SDK and Sentry, that might be affecting it? What would be the best way to debug lifecycle of service-worker?

Oliver Dunk

unread,
May 14, 2024, 9:26:46 AMMay 14
to Adnan Khan, Chromium Extensions
Unfortunately there isn't a specific way to see what is extending the lifetime of a service worker.

Could you try doing a sort of bisect, and slowly removing things like Supabase and Sentry to see if they have an impact?

Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

Adnan Khan

unread,
May 14, 2024, 9:37:07 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
Sure, I will do bisect method and will inform you in this thread. Thanks alot for reply!

Adnan Khan

unread,
May 14, 2024, 9:38:30 AMMay 14
to Chromium Extensions, Adnan Khan, Oliver Dunk, Chromium Extensions
Also just to confirm, if I don't open service-worker file, and test this through "Load Unpacked", would that behave the same as Chrome webstore installation? In terms of service-worker lifecycle.

Oliver Dunk

unread,
May 14, 2024, 9:44:13 AMMay 14
to Adnan Khan, Chromium Extensions
Yes, I don't believe there are any differences there that would be significant here.

If you'd like to be as close as possible to a web store installation, you can use the extension update testing tool which allows you to install a packed extension: https://github.com/GoogleChromeLabs/extension-update-testing-tool
Oliver Dunk | DevRel, Chrome Extensions | https://developer.chrome.com/ | London, GB

wOxxOm

unread,
May 14, 2024, 10:17:33 AMMay 14
to Chromium Extensions, Oliver Dunk, Chromium Extensions, Adnan Khan
* If you use WebSocket connection each message prolongs the lifetime by 30 seconds intentionally.
* Maybe your backgroundInitiation calls an asynchronous `chrome` API which has the same effect

Reply all
Reply to author
Forward
0 new messages