-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(element): service-worker helper
- Loading branch information
Showing
3 changed files
with
45 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import {createLogger} from '@alwatr/logger'; | ||
const logger = createLogger('service-worker'); | ||
|
||
export async function registerServiceWorker( | ||
path = 'service-worker.js', | ||
scope = '/', | ||
): Promise<ServiceWorkerRegistration | void> { | ||
logger.logMethodArgs('registerServiceWorker', {path, scope}); | ||
|
||
if (!('serviceWorker' in navigator)) { | ||
logger.incident('registerServiceWorker', 'sw_unsupported', 'Service worker not supported in this browser'); | ||
return; | ||
} | ||
|
||
try { | ||
const swRegistration = await navigator.serviceWorker.register(path); | ||
swRegistration.addEventListener('updatefound', () => swUpdateFound(swRegistration.installing)); | ||
logger.logOther('Service worker registered'); | ||
return swRegistration; | ||
} | ||
catch (err) { | ||
logger.error('registerServiceWorker', 'sw_reg_fail', 'Service worker registration failed'); | ||
} | ||
} | ||
|
||
function swUpdateFound(sw: ServiceWorker | null): void { | ||
if (sw == null) return; | ||
logger.logMethod('swUpdateFound'); | ||
sw.addEventListener('statechange', () => swStateChange(sw)); | ||
} | ||
|
||
function swStateChange(sw: ServiceWorker): void { | ||
logger.logMethodArgs('swStateChange', sw.state); | ||
if (sw.state === 'installed') { | ||
// if old controller available then its update else its new install | ||
if (navigator.serviceWorker.controller) { | ||
// send sw-updated signal; | ||
} | ||
} | ||
else if (sw.state === 'redundant') { | ||
logger.accident('swStateChange', 'sw_redundant', 'Service worker redundant'); | ||
} | ||
} |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters