ServiceWorker与indexedDB混合使用
- 背景
关于ServiceWorker中保存在内存中的变量, chromium的v67.0.3396.0的版本,当关闭chromium后,再重新启动时,保存在serviceWorker内存中的变量会被初始化,但是在chrome中没有此问题。为了解决这个问题,将保存在serviceWorker内存中的变量,放到indexedDB中保存
- serviceWorker无法访问web storage,因此不能用localStorage
- 客户用的浏览器时基于chromium进行的二次开发
- 将代码记录下,方便日后查看
var STATIC_CACHE_KEY = 'cache-key';
var MANIFEST_URL = "windows.cachemanifest";
var ORIGIN = location.href.replace("/service-worker.js", "");
var PREFIX = "【ServiceWorker】";
var cashUrlList;
var initFlag = false;
var updateReadyFlag = false;
console.log("##sw reload. updateReadyFlag is ##", updateReadyFlag);
var _VERSION = 1;
var _indexedDB = null;
var _DBNAME = "sw_IDB"
var _STORENAME = "sw_store";
function successCallback(data) {
};
function errorCallbck(error) {
var message = PREFIX + "IDB_ERROR_CALLBACK:";
if (error) {
message = message + error;
}
console.log(message);
};
self.addEventListener('install', function(event) {
console.log(PREFIX + "sw is installing !");
initFlag = true;
updateReadyFlag = true;
event.waitUntil(
openDataBase(_DBNAME, _STORENAME, _VERSION)
.then(function(db){
_indexedDB = db;
setUpdateReadyFlag(updateReadyFlag)
.then(successCallback, errorCallbck);
}, errorCallbck));
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function(event) {
console.log(PREFIX + "sw is actived !");
event.waitUntil(clients.claim());
event.waitUntil(
check_manifest()
);
});
self.addEventListener('message', function(event) {
if (event.data && event.data.length > 0) {
var message = event.data;
console.log(PREFIX + "message from Client=" + message);
switch (message) {
case 'init':
initFlag = true;
break;
case 'interval':
initFlag = false;
break;
default:
break;
}
getUpdateReadyFlag()
.then(function(value){
updateReadyFlag = value;
}, errorCallbck);
}
});
function load_manifest() {
return fetch(ORIGIN + "/" + MANIFEST_URL, {
cache: 'no-cache' })
.then(function(response) {
if (!response.ok) {
throw {
'status': response.status, 'message': response.statusText};
}
return response.text();
})
.then(function(content) {
return getCacheUrlList(content);
})
.catch(function(error) {
console.log(PREFIX + 'fetch request[2] error = ' + error.status + ':' + error.message);
clientPostMessege('error');
throw error;
});
}
function getCacheUrlList(content) {
content = content.replace(