我正在尝试使用 Webpack 在 Vuejs 上配置自定义服务人员,但它不能完全使用事件或工作箱(取决于我在哪里调用 sw.js 文件。
按照 Google 的工作箱指南,我已将 SW 配置为注册和缓存数据,但正如我之前提到的,取决于我调用 SW 的位置,它做错了事情(或者我可能只是愚蠢)。
例如,如果我像这样在index.html上注册文件 SW :
索引.html
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('service-worker.js').then(registration => {
// registration.pushManager.subscribe({ userVisibleOnly: true,
// applicationServerKey: key });
console.log('SW registered: ', registration);
}).catch(registrationError => {
console.log('SW registration failed: ', registrationError);
});
});
}
</script>
...我的 SW 已注册,但无法在下面显示的 SW 文件(service-worker.js)上捕获事件(离线和在线),但我可以使用工作箱:
服务工作者.js
import store from './store/index';
window.addEventListener('online', () => {
console.log('Ando online compa');
store.dispatch('IndexedDB/prueba');
});
window.addEventListener('offline', () => {
console.log('Ando offline compa');
store.dispatch('IndexedDB/prueba');
});
window.addEventListener('push', (event) => {
const title = 'Get Started With Workbox';
const options = {
body: event.data.text(),
};
event.waitUntil(window.registration.showNotification(title, options));
});
workbox.core.skipWaiting();
workbox.core.clientsClaim();
workbox.precaching.precacheAndRoute(self.__precacheManifest);
...如果我从index.html中删除脚本标记并调用main.js并像这样修改service-worker.js:
main.js
import './vapidHelper';
import Vue from 'vue';
import './plugins/vuetify';
import VueSocketIO from 'vue-socket.io';
import App from './App.vue';
import router from './router';
import store from './store';
import './axiosConfig';
import initDB from './indexedDB/IndexedDB';
import './service-worker'; // <---- LINE
Vue.config.productionTip = false;
...
服务工作者.js
import store from './store/index';
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('service-worker.js').then((registration) => {
// registration.pushManager.subscribe({ userVisibleOnly: true,
// applicationServerKey: key });
console.log('SW registered: ', registration);
}).catch((registrationError) => {
console.log('SW registration failed: ', registrationError);
});
});
window.addEventListener('online', () => {
console.log('Ando online compa');
store.dispatch('IndexedDB/prueba');
});
window.addEventListener('offline', () => {
console.log('Ando offline compa');
store.dispatch('IndexedDB/prueba');
});
window.addEventListener('push', (event) => {
const title = 'Get Started With Workbox';
const options = {
body: event.data.text(),
};
event.waitUntil(window.registration.showNotification(title, options));
});
}
workbox.core.skipWaiting();
workbox.core.clientsClaim();
workbox.precaching.precacheAndRoute(self.__precacheManifest);
...在这种情况下,我能够听到这些事件,但我无法使用工作箱(我在控制台上收到一个未定义的错误。)
你知道什么可能做错了吗?