fix: service worker access

This commit is contained in:
zerosoul
2022-06-12 12:21:12 +08:00
parent 86ea895b13
commit 14b4678d9e
2 changed files with 44 additions and 36 deletions
@@ -4,6 +4,8 @@ import { getToken, getMessaging } from "firebase/messaging";
import { firebaseConfig } from "../../../app/config"; import { firebaseConfig } from "../../../app/config";
const useDeviceToken = (vapidKey) => { const useDeviceToken = (vapidKey) => {
const [token, setToken] = useState(null); const [token, setToken] = useState(null);
// https only
if (navigator.serviceWorker) {
const messaging = getMessaging(initializeApp(firebaseConfig)); const messaging = getMessaging(initializeApp(firebaseConfig));
getToken(messaging, { getToken(messaging, {
@@ -25,6 +27,7 @@ const useDeviceToken = (vapidKey) => {
.catch((err) => { .catch((err) => {
console.log("An error occurred while retrieving token. ", err); console.log("An error occurred while retrieving token. ", err);
}); });
}
return token; return token;
}; };
export default useDeviceToken; export default useDeviceToken;
+22 -17
View File
@@ -11,15 +11,17 @@
// opt-in, read https://cra.link/PWA // opt-in, read https://cra.link/PWA
const isLocalhost = Boolean( const isLocalhost = Boolean(
window.location.hostname === 'localhost' || window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address. // [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' || window.location.hostname === "[::1]" ||
// 127.0.0.0/8 are considered localhost for IPv4. // 127.0.0.0/8 are considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
); );
export function register(config) { export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW. // The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) { if (publicUrl.origin !== window.location.origin) {
@@ -29,7 +31,7 @@ export function register(config) {
return; return;
} }
window.addEventListener('load', () => { window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) { if (isLocalhost) {
@@ -40,8 +42,8 @@ export function register(config) {
// service worker/PWA documentation. // service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => { navigator.serviceWorker.ready.then(() => {
console.log( console.log(
'This web app is being served cache-first by a service ' + "This web app is being served cache-first by a service " +
'worker. To learn more, visit https://cra.link/PWA' "worker. To learn more, visit https://cra.link/PWA"
); );
}); });
} else { } else {
@@ -53,6 +55,7 @@ export function register(config) {
} }
function registerValidSW(swUrl, config) { function registerValidSW(swUrl, config) {
if (!navigator.serviceWorker) return;
navigator.serviceWorker navigator.serviceWorker
.register(swUrl) .register(swUrl)
.then((registration) => { .then((registration) => {
@@ -62,14 +65,14 @@ function registerValidSW(swUrl, config) {
return; return;
} }
installingWorker.onstatechange = () => { installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') { if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) { if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched, // At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older // but the previous service worker will still serve the older
// content until all client tabs are closed. // content until all client tabs are closed.
console.log( console.log(
'New content is available and will be used when all ' + "New content is available and will be used when all " +
'tabs for this page are closed. See https://cra.link/PWA.' "tabs for this page are closed. See https://cra.link/PWA."
); );
// Execute callback // Execute callback
@@ -80,7 +83,7 @@ function registerValidSW(swUrl, config) {
// At this point, everything has been precached. // At this point, everything has been precached.
// It's the perfect time to display a // It's the perfect time to display a
// "Content is cached for offline use." message. // "Content is cached for offline use." message.
console.log('Content is cached for offline use.'); console.log("Content is cached for offline use.");
// Execute callback // Execute callback
if (config && config.onSuccess) { if (config && config.onSuccess) {
@@ -92,21 +95,21 @@ function registerValidSW(swUrl, config) {
}; };
}) })
.catch((error) => { .catch((error) => {
console.error('Error during service worker registration:', error); console.error("Error during service worker registration:", error);
}); });
} }
function checkValidServiceWorker(swUrl, config) { function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page. // Check if the service worker can be found. If it can't reload the page.
fetch(swUrl, { fetch(swUrl, {
headers: { 'Service-Worker': 'script' }, headers: { "Service-Worker": "script" },
}) })
.then((response) => { .then((response) => {
// Ensure service worker exists, and that we really are getting a JS file. // Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type'); const contentType = response.headers.get("content-type");
if ( if (
response.status === 404 || response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1) (contentType != null && contentType.indexOf("javascript") === -1)
) { ) {
// No service worker found. Probably a different app. Reload the page. // No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then((registration) => { navigator.serviceWorker.ready.then((registration) => {
@@ -120,12 +123,14 @@ function checkValidServiceWorker(swUrl, config) {
} }
}) })
.catch(() => { .catch(() => {
console.log('No internet connection found. App is running in offline mode.'); console.log(
"No internet connection found. App is running in offline mode."
);
}); });
} }
export function unregister() { export function unregister() {
if ('serviceWorker' in navigator) { if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready navigator.serviceWorker.ready
.then((registration) => { .then((registration) => {
registration.unregister(); registration.unregister();