【问题标题】:How to retrieve data from indexedDB in service worker?如何从服务工作者的 indexedDB 中检索数据?
【发布时间】:2017-11-17 20:36:58
【问题描述】:

我已将 json 数据存储在 indexedDB 中,并希望在服务工作者中应用程序请求它时检索它,但我收到一条错误消息,提示为服务工作者获取脚本时出错。 我的 Service Worker 代码是这样的:

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 正在做什么。当您发布使用包装 indexedDB 的库并且不包含库的相关部分或明确检查库的位置的代码时,很难回答有关 indexedDB 的问题。
  • Jake Archibald 的 idb 库。它在 GitHub 上。
  • 您能发布您看到的确切错误消息吗?
  • "获取脚本时发生未知错误。service_worker.js:1"

标签: javascript caching indexeddb service-worker fetch-api


【解决方案1】:

我的猜测是你需要从你的网站的根目录正确地路径你的 idb.js 引用。示例:

importScripts('/js/idb.js');

【讨论】:

  • 和service worker在同一个目录路径
  • 检查您的网络瀑布以查看您正在缓存的 URL 上是否有任何 404。确保您可以隔离未找到的文件。我认为您的问题不在于 IDB,而在于找不到文件。
  • 我很困惑,我在另一个脚本中使用相同的文件方法并且它们在那里工作正常,它只是 sw。
猜你喜欢
  • 1970-01-01
  • 2019-06-15
  • 1970-01-01
  • 2019-08-31
  • 1970-01-01
  • 1970-01-01
  • 2017-07-09
  • 2017-04-18
  • 1970-01-01
相关资源
最近更新 更多