我想要一个serviceWorker来拦截我的一些URL。在这一点上,我只想让SW记录它正在做的事情。
我看到控制台日志显示SW正确初始化,但从未调用fetch侦听器。
到目前为止我尝试过的事情:
fetch检索我的JSON有效负载。/boot/app/3/的请求。我注册我的西南地区:
if ('serviceWorker' in navigator)
navigator.serviceWorker.register('sw-boot.js', {
scope: '/boot/app/3/'
});西南地区的代码是:
const CACHE = 'boot';
console.log('sw-boot.js');
self.addEventListener('activate', function () {
clients.claim();
console.log('Now ready to handle fetches!');
});
self.addEventListener('fetch', function (evt) {
console.log('The service worker is serving the asset.');
evt.respondWith(fromNetwork(evt.request, 400).catch(function () {
return fromCache(evt.request);
}));
});
function fromNetwork(request, timeout) {
console.log('fromNetwork');
return new Promise(function (fulfill, reject) {
var timeoutId = setTimeout(reject, timeout);
fetch(request).then(function (response) {
clearTimeout(timeoutId);
fulfill(response);
}, reject);
});
}
function fromCache(request) {
console.log('fromCache');
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}然后,我用以下方法获取我的URL:
if ('serviceWorker' in navigator)
return fetch(bootUrl, {credentials: 'same-origin'})
.then(res => res.json())
.then(json => {
$rootScope.$evalAsync(() => {
self.update(json);
done();
});
});发布于 2018-01-30 15:06:45
我可以判断的是,您的服务工作人员配置只会拦截从遵循url模式/boot/app/3/的页面发起的请求,例如,如果您有一个页面http://localhost:8080/boot/app/3/index.html,并且这个页面加载了一些资产,那么这些资产的网络请求将被服务工作者截获,否则如果您有一个类似的http://localhost:8080/index.html,那么服务工作者将无法截获请求,因为您在其注册过程中所使用的范围。
https://stackoverflow.com/questions/48381003
复制相似问题