From 079e7e50f177e4f5b42a7f2d39260c3396c33c04 Mon Sep 17 00:00:00 2001 From: tophf Date: Mon, 25 Jul 2022 19:23:38 +0300 Subject: [PATCH] retry API on browser startup automatically --- content/apply.js | 9 +-------- js/msg.js | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/content/apply.js b/content/apply.js index ec16eaf8..2146b18c 100644 --- a/content/apply.js +++ b/content/apply.js @@ -60,7 +60,7 @@ mqDark.onchange(mqDark); // Declare all vars before init() or it'll throw due to "temporal dead zone" of const/let - const ready = init(); + init(); // the popup needs a check as it's not a tab but can be opened in a tab manually for whatever reason if (!isTab) { @@ -190,13 +190,6 @@ }); break; - case 'backgroundReady': - ready.catch(err => - msg.isIgnorableError(err) - ? init() - : console.error(err)); - break; - case 'updateCount': updateCount(); break; diff --git a/js/msg.js b/js/msg.js index 308f25ac..ba0e65f0 100644 --- a/js/msg.js +++ b/js/msg.js @@ -23,6 +23,8 @@ tab: new Set(), extension: new Set(), }; + let bgReadySignal; + let bgReadying = new Promise(fn => (bgReadySignal = fn)); // TODO: maybe move into polyfill.js and hook addListener to wrap/unwrap automatically chrome.runtime.onMessage.addListener(onRuntimeMessage); @@ -119,6 +121,9 @@ } function onRuntimeMessage({data, target}, sender, sendResponse) { + if (bgReadying && data && data.method === 'backgroundReady') { + bgReadySignal(); + } const res = msg._execute(TARGETS[target] || TARGETS.all, data, sender); if (res instanceof Promise) { res.then(wrapData, wrapError).then(sendResponse); @@ -148,6 +153,19 @@ : data; } + async function sendRetry(m) { + try { + return await msg.send(m); + } catch (e) { + if (!bgReadying || !msg.isIgnorableError(e)) { + return Promise.reject(e); + } + await bgReadying; + bgReadying = bgReadySignal = null; + return msg.send(m); + } + } + const apiHandler = !msg.isBg && { get({path}, name) { const fn = () => {}; @@ -161,7 +179,7 @@ let res; // content scripts, probably private tabs, and our extension tab during Chrome startup if (!bg || !bg.msg || !bg.msg.ready && await bg.bgReady.all && false) { - res = msg.send(message); + res = bgReadying ? sendRetry(message) : msg.send(message); } else { res = deepCopy(await bg.msg._execute(TARGETS.extension, message, { // Using a fake id for our Options frame as we want to fetch styles early