我是服务人员的新手,正在使用一个版本的Create-React-App作为入门模板。我需要将来自客户端内存的JSON数据存储到Service Worker存储中。 LocalStorage API没有足够的内存。
我尝试按照推荐的方式使用/登录“ self”,但是它在任何地方都没有显示为可访问变量。我当然会出错。
我正在使用xmlhttp请求下载数据,因为获取api没有进度条功能/加载完成。由于服务人员不支持xmlhttp,因此我必须手动编写此代码以将其传递。
我想可以使请求起源于服务工作者本身,但出于支持的原因,我希望逻辑保留在主客户端中。
请告诉我如何访问全局服务工作者范围,因为“自我”和“此”似乎不起作用,这让我非常生气。
index.js:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'connected-react-router';
import store, { history } from './store';
import App from './components/app';
import * as serviceWorker from './serviceWorker';
import 'sanitize.css/sanitize.css';
import './index.css';
render(
<html lang="en">
<head>
<meta httpEquiv="Content-Type" content="text/html; charset=UTF-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name='description' content='3D Earthquake Visualization of the United States GeoJSON Data Feeds. Built with React.js and Three.js by Javascript Developer Michael Paccione.' />
<meta name="author" content="Michael Paccione" />
<meta name="theme-color" content="#ffffff" />
<title>Quake Viz</title>
<link rel="preconnect" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />
</head>
<body>
<Provider store={store}>
<ConnectedRouter history={history}>
<div>
<App />
</div>
</ConnectedRouter>
</Provider>
<noscript>Your browser does not support JavaScript!</noscript>
</body>
</html>,
document.querySelector('#root')
);
serviceWorker.register();
serviceWorker.js:
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read ...
console.log("outerThis");
console.log(this);
console.log("outerSelf");
console.log(self);
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(config) {
// if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// if ('serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https:...
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
// }
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
console.log("this");
console.log(this);
console.log("self");
console.log(self);
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https:...'
);
// addListeners();
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
addListeners();
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
const addListeners = () => {
// Custom Cache Listener
console.log("SERVICE WORKER addListeners");
// console.log(navigator);
// console.log(WorkerGlobalScope.self);
navigator.serviceWorker.onmessage = function(event){
console.log("SW Received Message");
console.log(event);
console.log(event.data);
event.ports[0].postMessage("SW Says Hello Back!");
if (event.data.requireData == true && 'caches' in window) {
// Check for cache'd data and load
// clients.matchAll().then(clients => {
// clients.forEach(client => {
// console.log(client);
// //send_message_to_client(client, msg).then(m => console.log("SW Received Message: "+m));
// })
// })
//
caches.open('threeData').then(function(cache){
console.log("SW Cache");
console.log(cache)
event.ports[0].postMessage(cache);
});
} else {
// Cache Data
caches.open('threeData').then(function(cache){
cache.put('/data.json', new Response(event.data.json))
});
}
};
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}