overleaf/services/web/frontend/js/ide/pdfng/directives/serviceWorkerManager.js
Jakob Ackermann e8bb0114f8 Merge pull request #4203 from overleaf/bg-admin-disable-service-worker
disable service worker via admin page

GitOrigin-RevId: 96ec9f07b32b831f5271827ab345ad831044f831
2021-06-17 02:09:06 +00:00

57 lines
1.6 KiB
JavaScript

import { captureException } from '../../../infrastructure/error-reporter'
const OError = require('@overleaf/o-error')
let pendingWorkerSetup = Promise.resolve()
function supportsServiceWorker() {
return 'serviceWorker' in navigator
}
export function waitForServiceWorker() {
return pendingWorkerSetup
}
export function loadServiceWorker() {
if (supportsServiceWorker()) {
pendingWorkerSetup = navigator.serviceWorker
.register('/serviceWorker.js', {
scope: '/project/',
})
.then(() => {
navigator.serviceWorker.addEventListener('message', event => {
let ctx
try {
ctx = JSON.parse(event.data)
} catch (e) {
return
}
if (!ctx || !ctx.error || !ctx.extra) return
const err = OError.tag(ctx.error, 'Error in serviceWorker')
const fullError = new Error()
fullError.name = err.name
fullError.message = err.message
fullError.stack = OError.getFullStack(err)
captureException(fullError, { extra: ctx.extra })
})
})
.catch(error =>
captureException(OError.tag(error, 'Cannot register serviceWorker'))
)
}
}
export function unregisterServiceWorker() {
if (supportsServiceWorker()) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
type: 'disable',
})
}
navigator.serviceWorker.getRegistrations().then(registrations => {
registrations.forEach(worker => {
worker.unregister()
})
})
}
}