2021-06-09 09:45:55 -04:00
|
|
|
import { captureException } from '../../../infrastructure/error-reporter'
|
|
|
|
const OError = require('@overleaf/o-error')
|
|
|
|
|
2021-05-17 05:38:18 -04:00
|
|
|
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/',
|
|
|
|
})
|
2021-06-09 09:45:55 -04:00
|
|
|
.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'))
|
|
|
|
)
|
2021-05-17 05:38:18 -04:00
|
|
|
}
|
|
|
|
}
|
2021-06-16 04:14:18 -04:00
|
|
|
|
|
|
|
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()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|