From 5041e82980c7b6694d534a5d24310cae492fd166 Mon Sep 17 00:00:00 2001 From: Pavel Djundik Date: Tue, 23 Jul 2019 15:31:26 +0300 Subject: [PATCH] Send service worker fetch errors to client --- client/js/loading-error-handlers.js | 16 +++++++++++++++- client/service-worker.js | 11 +++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/client/js/loading-error-handlers.js b/client/js/loading-error-handlers.js index cf40644f..d6c118c6 100644 --- a/client/js/loading-error-handlers.js +++ b/client/js/loading-error-handlers.js @@ -9,7 +9,7 @@ */ (function() { - const msg = document.getElementById("loading-page-message"); + var msg = document.getElementById("loading-page-message"); if (msg) { msg.textContent = "Loading the app…"; @@ -69,5 +69,19 @@ // Trigger early service worker registration if ("serviceWorker" in navigator) { navigator.serviceWorker.register("service-worker.js"); + + // Handler for messages coming from the service worker + var messageHandler = function ServiceWorkerMessageHandler(event) { + if (event.data.type === "fetch-error") { + window.g_LoungeErrorHandler({ + message: `Service worker failed to fetch an url: ${event.data.message}`, + }); + + // Display only one fetch error + navigator.serviceWorker.removeEventListener("message", messageHandler); + } + }; + + navigator.serviceWorker.addEventListener("message", messageHandler); } })(); diff --git a/client/service-worker.js b/client/service-worker.js index 486f79f3..af8021fa 100644 --- a/client/service-worker.js +++ b/client/service-worker.js @@ -87,6 +87,17 @@ async function networkOrCache(event) { // eslint-disable-next-line no-console console.error(e.message, event.request.url); + if (event.clientId) { + const client = await clients.get(event.clientId); + + if (client) { + client.postMessage({ + type: "fetch-error", + message: e.message, + }); + } + } + const cache = await caches.open(cacheName); const matching = await cache.match(event.request);