Javascript 如何在service worker中从indexedDB检索数据?
我已将json数据存储在indexedDB中,并希望在应用程序在service worker中请求json数据时检索该数据,但我收到一个错误,即获取service worker脚本时出错。 我的服务人员代码如下所示:Javascript 如何在service worker中从indexedDB检索数据?,javascript,caching,indexeddb,service-worker,fetch-api,Javascript,Caching,Indexeddb,Service Worker,Fetch Api,我已将json数据存储在indexedDB中,并希望在应用程序在service worker中请求json数据时检索该数据,但我收到一个错误,即获取service worker脚本时出错。 我的服务人员代码如下所示: importScripts('idb.js'); const cache_v = 'a2', cache_all = [ 'shell_'+cache_v, 'data_'+cache_v ], statics = [ 'index.html', 'app.js', 'idb.j
importScripts('idb.js');
const cache_v = 'a2',
cache_all = [
'shell_'+cache_v,
'data_'+cache_v
],
statics = [
'index.html',
'app.js',
'idb.js'
];
this.addEventListener('install',e=>{
console.log("Installing Service Worker");
console.log("Storing Static Data");
e.waitUntil(
caches.open(cache_all[0])
.then(cac=>cac.addAll(statics))
.catch(er=>console.error(er))
)
console.log("Installation Complete");
});
this.addEventListener('activate',e=>{
console.log("Service worker activated, now clearing obsolete data");
})
this.addEventListener('fetch',e=>{
if(e.request.url === 'https://api.github.com/users/abt10/repos'){
console.log("IndexDB Reqrd");
let db = idb.open('Projects_info')
.then(d=>{
let ob = d.transaction('proj_dat');
let data = ob.objectStore('proj_dat');
let fd = data.getAll()
.then(dt=>{
return dt;
})
})
}
else{
e.respondWith(caches.match(e.request)
.then((res)=>{
return res || fetch(e.request).then(res=>{if(res.status === 404)
return new Response("Not Found");});
})
)
}
console.log('fetched');
})
我找不到错误所在。我猜您需要从网站的根目录正确地设置idb.js引用的路径。例如:
importScripts('/js/idb.js');
需要看看idb.js在做什么。如果您发布的代码使用了封装indexedDB的库,但不包含库的相关部分,或者Jake Archibald的library.idb library没有说明在哪里可以查看,那么很难回答有关indexedDB的问题。它在GitHub上。您能发布您看到的确切错误消息吗?“获取脚本时发生未知错误。service_worker.js:1”它与服务工作人员位于同一目录路径中检查您的网络瀑布,查看您正在缓存的URL上是否有404。确保可以隔离未找到的文件。我想你的问题不是IDB,而是找不到文件。我很困惑,我在另一个脚本中使用了相同的文件方法,它们在那里工作得很好,只是软件。