我正在尝试Service Worker在测试页面中实现一个.我的最终目标是离线操作的应用程序.文件夹结构如下
/myApp
...
/static
/mod
/practice
service-worker.js
worker-directives.js
foopage.js
/templates
/practice
foopage.html
Run Code Online (Sandbox Code Playgroud)
我正在注册服务工作者,如下所示(内service-worker.js):
navigator.serviceWorker.register('../static/mod/practice/service-worker.js').then(function(reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
...
}
Run Code Online (Sandbox Code Playgroud)
在控制台中,我看到了
Registration succeeded. Scope is https://example.com/static/mod/practice/
如果我的页面位于https://example.com/practice/foopage,我是否需要确保我的service worker范围是https://example.com/practice/foopage?
如果我尝试在register函数调用中定义范围,如
navigator.serviceWorker.register('../static/mod/practice/service-worker.js', { scope: '/practice/foopage/' }).then(function(reg) {
...
}
Run Code Online (Sandbox Code Playgroud)
我收到了错误
Registration failed with SecurityError: Failed to register a ServiceWorker: The path of the provided scope ('/practice/foopage/') is not under the max scope allowed ('/static/mod/practice/'). Adjust …Run Code Online (Sandbox Code Playgroud) 我的目录如下.
public_html/
sw/
Run Code Online (Sandbox Code Playgroud)
"sw /"是我想要放置所有服务工作者的地方,但是那些服务工作者的范围是"public_html /"中的所有文件.
JS
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw/notifications.js', { scope: '../sw/' }).then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
};
</script>
Run Code Online (Sandbox Code Playgroud)
我如何允许这种范围?
我现在尝试在我的 angularjs 项目中首先使用 service-worker 作为离线。我的项目由自耕农搭建脚手架,将这些行放在 service-worker 中,如下所示。
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching App Shell');
return cache.addAll(filesToCache);
})
);
});
Run Code Online (Sandbox Code Playgroud)
并按如下方式调用并注册 service-worker index.jade
script.
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('app/service-worker.js')
.then(function() {
console.log('Service Worker Registered');
})
.catch(function(err) {
console.log('ServiceWorker registration failed: ', err);
});
}
Run Code Online (Sandbox Code Playgroud)
我收到了Service Worker Registered消息,但问题是addEventListener服务工作者在应用程序运行时不会被解雇。
self.addEventListener('install', function(e)
self.addEventListener('activate', function(event) {
self.addEventListener('fetch', function(e) {
Run Code Online (Sandbox Code Playgroud)
请帮我解决我错过的代码。