From 72b05cacacf433182272960d7892b2834631c35e Mon Sep 17 00:00:00 2001 From: Joe Previte Date: Thu, 11 Feb 2021 15:02:33 -0700 Subject: [PATCH] refactor: create registerServiceWorker fn --- src/browser/register.ts | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/src/browser/register.ts b/src/browser/register.ts index 4f834580..c975df87 100644 --- a/src/browser/register.ts +++ b/src/browser/register.ts @@ -1,18 +1,23 @@ -import { getOptions, normalize } from "../common/util" - -const options = getOptions() +import { getOptions, Options, normalize } from "../common/util" import "./pages/error.css" import "./pages/global.css" import "./pages/login.css" -if ("serviceWorker" in navigator) { - const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`) - navigator.serviceWorker - .register(path, { +export async function registerServiceWorker(navigator: Navigator, path: string, options: Options): Promise { + try { + await navigator.serviceWorker.register(path, { scope: (options.base ?? "") + "/", }) - .then(() => { - console.log("[Service Worker] registered") - }) + console.log("[Service Worker] registered") + } catch (error) { + console.error(`[Service Worker] failed to register: ${error.message}`) + } +} + +if (typeof navigator !== "undefined" && "serviceWorker" in navigator) { + const options = getOptions() + const path = normalize(`${options.csStaticBase}/dist/serviceWorker.js`) + registerServiceWorker(navigator, path, options) + } }