DEV: Export register service worker logic (#14598)

This commit is contained in:
Mark VanLandingham 2021-10-13 13:19:20 -05:00 committed by GitHub
parent 9ab9eda40e
commit 8b25aaed14
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 43 deletions

View File

@ -1,50 +1,10 @@
import getAbsoluteURL, { isAbsoluteURL } from "discourse-common/lib/get-url";
import { registerServiceWorker } from "discourse/lib/register-service-worker";
export default {
name: "register-service-worker",
initialize(container) {
const isSecured = document.location.protocol === "https:";
if (isSecured && "serviceWorker" in navigator) {
let { serviceWorkerURL } = container.lookup("session:main");
const caps = container.lookup("capabilities:main");
const isAppleBrowser =
caps.isSafari ||
(caps.isIOS &&
!window.matchMedia("(display-mode: standalone)").matches);
if (serviceWorkerURL && !isAppleBrowser) {
navigator.serviceWorker.getRegistrations().then((registrations) => {
for (let registration of registrations) {
if (
registration.active &&
!registration.active.scriptURL.includes(serviceWorkerURL)
) {
this.unregister(registration);
}
}
});
navigator.serviceWorker
.register(getAbsoluteURL(`/${serviceWorkerURL}`))
.catch((error) => {
// eslint-disable-next-line no-console
console.info(`Failed to register Service Worker: ${error}`);
});
} else {
navigator.serviceWorker.getRegistrations().then((registrations) => {
for (let registration of registrations) {
this.unregister(registration);
}
});
}
}
},
unregister(registration) {
if (isAbsoluteURL(registration.scope)) {
registration.unregister();
}
let { serviceWorkerURL } = container.lookup("session:main");
registerServiceWorker(container, serviceWorkerURL);
},
};

View File

@ -0,0 +1,44 @@
import getAbsoluteURL, { isAbsoluteURL } from "discourse-common/lib/get-url";
export function registerServiceWorker(container, serviceWorkerURL) {
const isSecured = document.location.protocol === "https:";
if (isSecured && "serviceWorker" in navigator) {
const caps = container.lookup("capabilities:main");
const isAppleBrowser =
caps.isSafari ||
(caps.isIOS && !window.matchMedia("(display-mode: standalone)").matches);
if (serviceWorkerURL && !isAppleBrowser) {
navigator.serviceWorker.getRegistrations().then((registrations) => {
for (let registration of registrations) {
if (
registration.active &&
!registration.active.scriptURL.includes(serviceWorkerURL)
) {
unregister(registration);
}
}
});
navigator.serviceWorker
.register(getAbsoluteURL(`/${serviceWorkerURL}`))
.catch((error) => {
// eslint-disable-next-line no-console
console.info(`Failed to register Service Worker: ${error}`);
});
} else {
navigator.serviceWorker.getRegistrations().then((registrations) => {
for (let registration of registrations) {
unregister(registration);
}
});
}
}
}
function unregister(registration) {
if (isAbsoluteURL(registration.scope)) {
registration.unregister();
}
}