Я сохранил данные в indexeddb. Я кеширую активы по работникам. Работает нормально. Теперь я хочу кешировать данные indexeddb с помощью serviceworker. Я пытался до сих пор, но это не работает. Вот мой код сервисной работы:
serviceworker
'use strict';
const precacheVersion = 1;
const precacheName = 'precache-v' + precacheVersion;
const offlinePage =['index.html',
'css/common.css',
'css/fader.png',
'css/Save.gif'
];
self.addEventListener('install', (e) => {
console.log('[ServiceWorker] Installed');
self.skipWaiting();
e.waitUntil(
caches.open(precacheName).then((cache) => {
console.log('[ServiceWorker] Precaching files');
return cache.addAll(offlinePage);
})
);
});
self.addEventListener('activate', (e) => {
console.log('[ServiceWorker] Activated');
e.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(cacheNames.map((thisCacheName) => {
if (thisCacheName.includes("precache") && thisCacheName !== precacheName) {
console.log('[ServiceWorker] Removing cached files from old cache - ', thisCacheName);
return caches.delete(thisCacheName);
}
}));
})
);
});
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(currentCache.offline);
const cachedResponse = await cache.match(offlinePage);
return cachedResponse;
}
})());
}
});
вот файл idb idb. js
$(document).ready(function () {
var db_name = 'mobileClaimsDb',
store_name = 'claims';
$.ajax({
url: 'index.cfm?action=main.appcache',
type: 'post',
cache:true,
success: function (data) {
var request,
upgrade = false,
doTx = function (db, entry) {
addData(db, entry, function () {
getData(db);
});
},
getData = function (db) {
db.transaction([store_name], "readonly").objectStore(store_name).openCursor(IDBKeyRange.lowerBound(0)).onsuccess = function (event) {
var cursor = event.target.result;
if (null !== cursor) {
console.log("entry", cursor.value);
cursor.continue();
}
};
},
addData = function (db, entry, finished) {
console.log('adding', entry);
var tx = db.transaction([store_name], "readwrite"),
claims = [];
tx.addEventListener('complete', function (e) {
finished();
});
$.each(claims, function (key, value) {
tx.objectStore(store_name).add(value);
});
};
request = window.indexedDB.open(db_name);
request.oncomplete = function (event) {
if (upgrade) {
doTx(request.result, data);
}
};
request.onsuccess = function (event) {
if (!upgrade) {
doTx(request.result, data);
}
};
request.onupgradeneeded = function (event) {
var db = event.target.result;
db.createObjectStore('claims', {
keyPath: null,
autoIncrement: true
});
}
}
});
});
Какие изменения необходимы для чтения данных idb и их кэширования?