From b5f2de89541328f496b77ddf20843c10cd9391ed Mon Sep 17 00:00:00 2001 From: Brayo Date: Wed, 31 Dec 2025 17:31:22 +0300 Subject: [PATCH] wip, fix chrome sleep issues --- src/background/main.ts | 35 +++++++++++++++++------------------ src/offscreen/offscreen.html | 10 ++++++++++ src/offscreen/offscreen.ts | 5 +++++ vite.config.ts | 6 +++++- 4 files changed, 37 insertions(+), 19 deletions(-) create mode 100644 src/offscreen/offscreen.html create mode 100644 src/offscreen/offscreen.ts diff --git a/src/background/main.ts b/src/background/main.ts index a1b092b..8f54957 100644 --- a/src/background/main.ts +++ b/src/background/main.ts @@ -82,24 +82,23 @@ setBaseUrl(client.baseURL) * https://stackoverflow.com/questions/66618136 */ if (import.meta.env.VITE_TARGET_BROWSER === 'chrome') { - function setupKeepAlive(): void { - console.debug( - 'Setting up keep-alive ping to prevent service worker termination', - ) - - setInterval( - () => { - console.debug('Keep-alive ping') - // Force some minimal activity - browser.alarms - .get(config.heartbeat.alarmName) - .then(() => console.debug('Keep-alive ping completed')) - .catch((err) => console.error('Keep-alive ping failed:', err)) - }, - 4 * 60 * 1000, - ) // 4 minutes (less than Chrome's ~5 minute timeout) + console.debug('Setting up offscreen keep-alive') + const createOffscreen = async () => { + // @ts-ignore + if (await chrome.offscreen.hasDocument()) return + // @ts-ignore + await chrome.offscreen.createDocument({ + url: 'src/offscreen/offscreen.html', + reasons: ['BLOBS'], // BLOBS or AUDIO_PLAYBACK + justification: 'keep service worker running', + }) } - // Start the keep-alive mechanism - setupKeepAlive() + // @ts-ignore + chrome.runtime.onStartup.addListener(createOffscreen) + createOffscreen() + // @ts-ignore + chrome.runtime.onMessage.addListener((msg) => { + if (msg.keepAlive) console.debug('keepAlive') + }) } diff --git a/src/offscreen/offscreen.html b/src/offscreen/offscreen.html new file mode 100644 index 0000000..77bcefd --- /dev/null +++ b/src/offscreen/offscreen.html @@ -0,0 +1,10 @@ + + + + + Offscreen + + + + + diff --git a/src/offscreen/offscreen.ts b/src/offscreen/offscreen.ts new file mode 100644 index 0000000..e58b587 --- /dev/null +++ b/src/offscreen/offscreen.ts @@ -0,0 +1,5 @@ +declare var chrome: any + +setInterval(() => { + chrome.runtime.sendMessage({ keepAlive: true }) +}, 20000) diff --git a/vite.config.ts b/vite.config.ts index c7dde5b..a5f248e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -20,7 +20,11 @@ export default defineConfig({ plugins: [ webExtension({ manifest: generateManifest, - additionalInputs: ['src/consent/index.html', 'src/consent/main.ts'], + additionalInputs: [ + 'src/consent/index.html', + 'src/consent/main.ts', + 'src/offscreen/offscreen.html', + ], browser: process.env.VITE_TARGET_BROWSER, }), ],