[英]Service Worker not being register in Angular
I want to do a push notification to my Angular app.我想向我的 Angular 应用程序发送推送通知。 I'm doing it with vanilla js and not with the Angular service worker or @angular/pwa.
我正在使用 vanilla js 而不是 Angular 服务工作者或@angular/pwa。
I added the path of the js file in the script option in angular.json.我在angular.json的脚本选项中添加了js文件的路径。 When the service worker is going to be register it redirects the path from the root ( http://127.0.0.1:8887/sw.js ) and not from the folder that I place the file in.
当服务工作者要注册时,它会从根目录( http://127.0.0.1:8887/sw.js )重定向路径,而不是从我放置文件的文件夹。
This is the angular.json file:这是 angular.json 文件:
"scripts": [
"./src/assets/js/main.js",
"./src/assets/js/sw.js"
]
main.js file: main.js 文件:
const applicationServerPublicKey = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
let isSubscribed = false;
let swRegistration = null;
if ('serviceWorker' in navigator && 'PushManager' in window) {
console.log('Service Worker and Push is supported');
navigator.serviceWorker.register('/sw.js') // I tried ./sw.js and also /src/assets/js/sw.js and sw.js alone
.then(function(swReg) {
console.log('Service Worker is registered', swReg);
swRegistration = swReg;
})
.catch(function(error) {
console.error('Service Worker Error', error);
});
} else {
console.warn('Push messaging is not supported');
pushButton.textContent = 'Push Not Supported';
}
service worker file just for testing that the file is reachable by the moment:服务工作者文件仅用于测试该文件目前是否可以访问:
console.log('sw');
this is the error:这是错误:
Service Worker Error TypeError: Failed to register a ServiceWorker for scope ('http://127.0.0.1:8887/') with script ('http://127.0.0.1:8887/sw.js'): A bad HTTP response code (404) was received when fetching the script.
The issue was resolve, I had to add the path /assets/js/sw.js
to the navigator.serviceWorker.register('/assets/js/sw.js')
问题已解决,我必须将路径
/assets/js/sw.js
添加到navigator.serviceWorker.register('/assets/js/sw.js')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.