Javascript 服务人员基本设置

Javascript 服务人员基本设置,javascript,html,service-worker,Javascript,Html,Service Worker,我有以下服务人员代码: 'use strict'; // Incrementing CACHE_VERSION will kick off the install event and force previously cached // resources to be cached again. const CACHE_VERSION = 1; let CURRENT_CACHES = { offline: 'offline-v' + CACHE_VERSION }; const OF

我有以下服务人员代码:

'use strict';

// Incrementing CACHE_VERSION will kick off the install event and force previously cached
// resources to be cached again.
const CACHE_VERSION = 1;
let CURRENT_CACHES = {
    offline: 'offline-v' + CACHE_VERSION
};
const OFFLINE_URL = 'offline.php';

function createCacheBustedRequest(url) {
    let request = new Request(url, {cache: 'reload'});
    // See https://fetch.spec.whatwg.org/#concept-request-mode
    // This is not yet supported in Chrome as of M48, so we need to explicitly check to see
    // if the cache: 'reload' option had any effect.
    if ('cache' in request) {
        return request;
    }

    // If {cache: 'reload'} didn't have any effect, append a cache-busting URL parameter instead.
    let bustedUrl = new URL(url, self.location.href);
    bustedUrl.search += (bustedUrl.search ? '&' : '') + 'cachebust=' + Date.now();
    return new Request(bustedUrl);
}

self.addEventListener('install', event => {
    event.waitUntil(
        // We can't use cache.add() here, since we want OFFLINE_URL to be the cache key, but
        // the actual URL we end up requesting might include a cache-busting parameter.
        fetch(createCacheBustedRequest(OFFLINE_URL)).then(function(response) {
            return caches.open(CURRENT_CACHES.offline).then(function(cache) {
                return cache.put(OFFLINE_URL, response);
            });
        })
    );
});

self.addEventListener('activate', event => {
    // Delete all caches that aren't named in CURRENT_CACHES.
    // While there is only one cache in this example, the same logic will handle the case where
    // there are multiple versioned caches.
    let expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) {
        return CURRENT_CACHES[key];
    });

event.waitUntil(
    caches.keys().then(cacheNames => {
        return Promise.all(
            cacheNames.map(cacheName => {
                if (expectedCacheNames.indexOf(cacheName) === -1) {
    // If this cache name isn't present in the array of "expected" cache names,
    // then delete it.
    console.log('Deleting out of date cache:', cacheName);
    return caches.delete(cacheName);
}
})
);
})
);
});

self.addEventListener('fetch', event => {
    // We only want to call event.respondWith() if this is a navigation request
    // for an HTML page.
    // request.mode of 'navigate' is unfortunately not supported in Chrome
    // versions older than 49, so we need to include a less precise fallback,
    // which checks for a GET request with an Accept: text/html header.
    if (event.request.mode === 'navigate' ||
        (event.request.method === 'GET' &&
            event.request.headers.get('accept').includes('text/html'))) {
    console.log('Handling fetch event for', event.request.url);
    event.respondWith(
        fetch(createCacheBustedRequest(event.request.url)).catch(error => {
            // The catch is only triggered if fetch() throws an exception, which will most likely
            // happen due to the server being unreachable.
            // If fetch() returns a valid HTTP response with an response code in the 4xx or 5xx
            // range, the catch() will NOT be called. If you need custom handling for 4xx or 5xx
            // errors, see https://github.com/GoogleChrome/samples/tree/gh-pages/service-worker/fallback-response
            console.log('Fetch failed; returning offline page instead.', error);
    return caches.match(OFFLINE_URL);
})
);
}

// If our if() condition is false, then this fetch handler won't intercept the request.
// If there are any other fetch handlers registered, they will get a chance to call
// event.respondWith(). If no fetch handlers call event.respondWith(), the request will be
// handled by the browser as if there were no service worker involvement.
});

如何使它不必在缓存中保存任何内容?有问题的webapp需要随时连接。因此,该服务人员的主要目的是有资格安装电话,并具有以后的推送通知功能

经过一些在线研究,以下是最佳解决方案:

sw_install.js

    console.log('Started', self);
self.addEventListener('install', function(event) {
    self.skipWaiting();
    console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
    console.log('Activated', event);
});
self.addEventListener('push', function(event) {
    console.log('Push message received', event);
    // TODO
});
main.js

    if ('serviceWorker' in navigator) {
    console.log('Service Worker is supported');
    navigator.serviceWorker.register('sw_install.js').then(function(reg){
        console.log(':^)', reg);
        // TODO
    }).catch(function(err) {
        console.log(':^(', err);
    });
}

经过一些在线研究,以下是最佳解决方案:

sw_install.js

    console.log('Started', self);
self.addEventListener('install', function(event) {
    self.skipWaiting();
    console.log('Installed', event);
});
self.addEventListener('activate', function(event) {
    console.log('Activated', event);
});
self.addEventListener('push', function(event) {
    console.log('Push message received', event);
    // TODO
});
main.js

    if ('serviceWorker' in navigator) {
    console.log('Service Worker is supported');
    navigator.serviceWorker.register('sw_install.js').then(function(reg){
        console.log(':^)', reg);
        // TODO
    }).catch(function(err) {
        console.log(':^(', err);
    });
}

您可以使用npm sw工具箱库()

main.js

if(navigator.serviceWorker){
register('/service worker.js',{scope:'./'})
.然后(功能(注册){
控制台日志(“软件注册”,注册);
})
.catch(函数(e){
控制台。错误(“错误”,e);
})
}否则{
console.log('此浏览器不支持服务工作程序')
}
}
服务工作者.js

(全局=>{
"严格使用",;
//加载sw tookbox库。
importScripts('/js/sw toolbox.js');
var precache_url=[
“/index.html”,
“/img/logo.png”,
“/img/main.png”
];
//仅用于调试
global.toolbox.options.debug=true;
global.toolbox.router.get('/img/(.*),self.toolbox.cacheFirst{
缓存:{
名称:“图像”,
最大输入:10
}
});
global.toolbox.router.default=global.toolbox.networkFirst;
global.addEventListener('install',event=>event.waitill(global.skipWaiting());
global.addEventListener('activate',event=>event.waitUntil(global.clients.claim());
全局.addEventListener('push',事件=>{
var pushObj=event.data.json();
var pushData=pushObj.data;
//推送有效负载(如果有),如果没有,则进行ajax get调用以获取有效负载(可以使用fetch)
var title=pushData&&pushData.title;
var body=pushData&&pushData.body;
var icon='/img/logo.png';
event.waitUntil(全局注册)showNotification(标题{
身体:身体,,
图标:图标,
徽章:图标
数据:pushData
}));
});
global.addEventListener('notificationclick',事件=>{
event.notification.close();
var url=event.notification.data.url | |'/';
event.waitill(
客户。匹配球({
键入:“窗口”
})。然后(WindowClient=>{
console.log('WindowClients',WindowClients);
对于(var i=0;i
您可以使用npm sw工具箱库()

main.js

if(navigator.serviceWorker){
register('/service worker.js',{scope:'./'})
.然后(功能(注册){
控制台日志(“软件注册”,注册);
})
.catch(函数(e){
控制台。错误(“错误”,e);
})
}否则{
console.log('此浏览器不支持服务工作程序')
}
}
服务工作者.js

(全局=>{
"严格使用",;
//加载sw tookbox库。
importScripts('/js/sw toolbox.js');
var precache_url=[
“/index.html”,
“/img/logo.png”,
“/img/main.png”
];
//仅用于调试
global.toolbox.options.debug=true;
global.toolbox.router.get('/img/(.*),self.toolbox.cacheFirst{
缓存:{
名称:“图像”,
最大输入:10
}
});
global.toolbox.router.default=global.toolbox.networkFirst;
global.addEventListener('install',event=>event.waitill(global.skipWaiting());
global.addEventListener('activate',event=>event.waitUntil(global.clients.claim());
全局.addEventListener('push',事件=>{
var pushObj=event.data.json();
var pushData=pushObj.data;
//推送有效负载(如果有),如果没有,则进行ajax get调用以获取有效负载(可以使用fetch)
var title=pushData&&pushData.title;
var body=pushData&&pushData.body;
var icon='/img/logo.png';
event.waitUntil(全局注册)showNotification(标题{
身体:身体,,
图标:图标,
徽章:图标
数据:pushData
}));
});
global.addEventListener('notificationclick',事件=>{
event.notification.close();
var url=event.notification.data.url | |'/';
event.waitill(
客户。匹配球({
键入:“窗口”
})。然后(WindowClient=>{
console.log('WindowClients',WindowClients);
对于(var i=0;i
你不能,你知道,删除保存到缓存中的行吗?问题是,第一行代码中都使用了变量,所以我想知道,在以后的推送通知开发中,最基本的最小值是什么。
cache.put(离线URL,响应)这将把东西保存到缓存中。尝试删除它。你不能,你知道,删除保存到缓存中的行吗?问题是,第一行代码中都使用了变量,所以我想知道,在以后的推送通知开发中,最基本的最小值是什么。
cache.put(OFFLINE\u URL,response);