From d26858b6ad9856a5d43ae8965ed6c5dc98c31af6 Mon Sep 17 00:00:00 2001 From: Stefano Dissegna Date: Wed, 25 Aug 2021 09:08:24 +0200 Subject: [PATCH] backported https://github.com/microsoft/vscode/pull/131408 --- .../contrib/webview/browser/pre/main.js | 23 ++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/main.js b/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/main.js index 73555697d..2cbe115ce 100644 --- a/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/main.js +++ b/lib/vscode/src/vs/workbench/contrib/webview/browser/pre/main.js @@ -242,7 +242,28 @@ const workerReady = new Promise(async (resolve, reject) => { } }; navigator.serviceWorker.addEventListener('message', versionHandler); - assertIsDefined(registration.active).postMessage({ channel: 'version' }); + + const postVersionMessage = () => { + assertIsDefined(navigator.serviceWorker.controller).postMessage({ channel: 'version' }); + }; + + // At this point, either the service worker is ready and + // became our controller, or we need to wait for it. + // Note that navigator.serviceWorker.controller could be a + // controller from a previously loaded service worker. + const currentController = navigator.serviceWorker.controller; + if (currentController && currentController.scriptURL.endsWith(swPath)) { + // service worker already loaded & ready to receive messages + postVersionMessage(); + } else { + // either there's no controlling service worker, or it's an old one: + // wait for it to change before posting the message + const onControllerChange = () => { + navigator.serviceWorker.removeEventListener('controllerchange', onControllerChange); + postVersionMessage(); + }; + navigator.serviceWorker.addEventListener('controllerchange', onControllerChange); + } }, error => { reject(new Error(`Could not register service workers: ${error}.`));