Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to access indexeddb from service worker

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");
 }
 }
like image 726
Ravikrn Avatar asked Sep 25 '22 21:09

Ravikrn


1 Answers

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.

like image 137
Jeff Posnick Avatar answered Oct 12 '22 11:10

Jeff Posnick