I have stored data in indexeddb and I am trying to access this data in service worker. But request to open indexeddb is not done, it is pending. Hence, I am not able to access data. Need help in sorting out the issue. Below is my code to access data from service worker.
var idbSupported = false;
var db;
self.addEventListener('push', function(){
if("indexedDB" in self) {
idbSupported = true;
}else{ console.log('Indexed db not supported');}
if(idbSupported) {
var openRequest = indexedDB.open("test",1);
openRequest.onupgradeneeded = function(e) {
console.log("Upgrading...");
var thisDB = e.target.result;
if(!thisDB.objectStoreNames.contains("users")) {
thisDB.createObjectStore("users", { autoIncrement: true });
}
}
openRequest.onsuccess = function(e) {
console.log("Success!");
db = e.target.result;
readUser();
}
openRequest.onerror = function(e) {
console.log("Error");
console.dir(e);
}
}
},false);
function readUser(){
var transaction = db.transaction(["users"], "readwrite");
var store = transaction.objectStore("users");
var request = store.get(user_id);
request.onerror = function() {
console.log("Error");
}
request.onsuccess = function() {
console.log("Yolo! Did it");
}
}
If I take your code outside of a push
event listener and just run it unconditionally from within a service worker, it runs successfully. I'm not exactly sure what's causing what you're seeing, but perhaps the push
event isn't being triggered as you'd expect?
If you're looking for some general code showing off the use of IndexedDB from within a service worker, https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/offline-analytics/service-worker.js is a sample that might help. But I think the code that you posted basically does work.
As an aside, it shouldn't be necessary to check whether 'indexedDB' in self
from within your service worker. IndexedDB is available in both Chrome and Firefox's service worker implementations, and I'd very much assume that any other browsers which ship service workers in the future will also expose IndexedDB in their implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With