Failed to access indexeddb from service worker

I saved the data in indexeddb and I am trying to access this data in a service. But the request to open indexeddb is not executed, it is waiting for a response. Therefore, I cannot access the data. Need help sorting the problem. Below is my code for accessing data from a 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");
 }
 }
+4
source share
1 answer

If I take your code outside the event listener pushand just run it unconditionally from the work service, it works successfully. I'm not quite sure what causes what you see, but maybe the event pushdoesn't fire, as you expected?

- , IndexedDB , https://github.com/GoogleChrome/samples/blob/gh-pages/service-worker/offline-analytics/service-worker.js - , . , , , .

, , 'indexedDB' in self . IndexedDB Chrome, Firefox, , , - , IndexedDB .

+2

Source: https://habr.com/ru/post/1621284/


All Articles