mirror of
https://github.com/coderaiser/cloudcmd.git
synced 2026-01-23 02:35:49 +00:00
35 lines
835 B
JavaScript
35 lines
835 B
JavaScript
'use strict';
|
|
|
|
const {tryToCatch} = require('try-to-catch');
|
|
|
|
module.exports.registerSW = registerSW;
|
|
module.exports.unregisterSW = unregisterSW;
|
|
|
|
module.exports.listenSW = (sw, ...args) => {
|
|
sw?.addEventListener(...args);
|
|
};
|
|
|
|
async function registerSW(prefix) {
|
|
if (!navigator.serviceWorker)
|
|
return;
|
|
|
|
const isHTTPS = location.protocol === 'https:';
|
|
const isLocalhost = location.hostname === 'localhost';
|
|
|
|
if (!isHTTPS && !isLocalhost)
|
|
return;
|
|
|
|
const {serviceWorker} = navigator;
|
|
const register = serviceWorker.register.bind(serviceWorker);
|
|
const [e, sw] = await tryToCatch(register, `${prefix}/sw.js`);
|
|
|
|
if (e)
|
|
return null;
|
|
|
|
return sw;
|
|
}
|
|
|
|
async function unregisterSW(prefix) {
|
|
const reg = await registerSW(prefix);
|
|
reg?.unregister(prefix);
|
|
}
|