fix(bug): extension stuck in ... loading ... screen after service_worker got terminated (#1424)

* add background wakeup

* add background wakeup
This commit is contained in:
Alberto Nicolas Penayo 2024-07-30 18:00:40 -03:00 committed by GitHub
parent ba295ec0f4
commit 993d2eb5c9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 37 additions and 1 deletions

View File

@ -30,7 +30,37 @@ interface Handler {
type Handlers = Record<string, Handler>;
const port = chrome.runtime.connect({ name: PORT_EXTENSION });
async function wakeupBackground (): Promise<Error | null> {
try {
await chrome.runtime.sendMessage({ type: 'wakeup' });
return null;
} catch (cause) {
return cause instanceof Error ? cause : new Error(String(cause));
}
}
async function createPort (name: string, maxAttempts: number, delayMs: number): Promise<chrome.runtime.Port> {
let lastError: Error | null = null;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const error = await wakeupBackground();
if (error) {
lastError = error;
await new Promise((resolve) => setTimeout(resolve, delayMs));
continue;
}
const port = chrome.runtime.connect({ name });
return port;
}
throw new Error('Failed to create port after multiple attempts', { cause: lastError });
}
const port = await createPort(PORT_EXTENSION, 5, 1000);
const handlers: Handlers = {};
// setup a listener for messages, any incoming resolves the promise

View File

@ -50,6 +50,12 @@ function getActiveTabs () {
});
}
chrome.runtime.onMessage.addListener((message: { type: string }, _, sendResponse) => {
if (message.type === 'wakeup') {
sendResponse({ status: 'awake' });
}
});
// listen to tab updates this is fired on url change
chrome.tabs.onUpdated.addListener((_, changeInfo) => {
// we are only interested in url change