fix(cloudcmd) register service worker on http connection (#203)

This commit is contained in:
coderaiser 2018-11-01 19:20:55 +02:00
parent 7217b73e4a
commit b782c0aec1
3 changed files with 30 additions and 7 deletions

View file

@ -11,6 +11,7 @@ const load = require('load.js');
const {
registerSW,
listenSW,
} = require('./sw/register');
// prevent additional loading of emitify
@ -65,5 +66,6 @@ async function register(config) {
const {prefix} = config;
const sw = await registerSW(prefix);
sw.addEventListener('updatefound', onUpdateFound(config));
listenSW(sw, 'updatefound', onUpdateFound(config));
}

View file

@ -3,7 +3,9 @@
module.exports.registerSW = registerSW;
module.exports.unregisterSW = unregisterSW;
const noop = () => {};
module.exports.listenSW = (sw, ...args) => {
sw && sw.addEventListener(...args);
};
async function registerSW(prefix) {
if (!navigator.serviceWorker)
@ -13,15 +15,12 @@ async function registerSW(prefix) {
const isLocalhost = location.hostname === 'localhost';
if (!isHTTPS && !isLocalhost)
return {
addEventListener: noop,
};
return;
return navigator.serviceWorker.register(`${prefix}/sw.js`);
}
async function unregisterSW() {
const reg = await registerSW();
return reg.unregister();
reg && reg.unregister();
}

View file

@ -3,6 +3,28 @@
const test = require('tape');
const sinon = require('sinon');
const mock = require('mock-require');
const tryCatch = require('try-catch');
test('sw: listen', (t) => {
const {listenSW} = mock.reRequire('./register');
const addEventListener = sinon.stub();
const sw = {
addEventListener,
};
listenSW(sw, 'hello', 'world');
t.ok(addEventListener.calledWith('hello', 'world'), 'should call addEventListener');
t.end();
});
test('sw: lesten: no sw', (t) => {
const {listenSW} = mock.reRequire('./register');
const [e] = tryCatch(listenSW, null, 'hello', 'world');
t.notOk(e, 'should not throw');
t.end();
});
test('sw: register: registerSW: no serviceWorker', async (t) => {
const {navigator} = global;