Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 17 additions & 18 deletions src/background/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
}
10 changes: 10 additions & 0 deletions src/offscreen/offscreen.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Offscreen</title>
</head>
<body>
<script type="module" src="./offscreen.ts"></script>
</body>
</html>
5 changes: 5 additions & 0 deletions src/offscreen/offscreen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
declare var chrome: any

setInterval(() => {
chrome.runtime.sendMessage({ keepAlive: true })
}, 20000)
6 changes: 5 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}),
],
Expand Down
Loading