我已经将数据存储在IndexedDB中,现在想在Service Worker中访问这些数据。但是打开IndexedDB的请求一直处于等待状态,因此我无法访问数据。需要帮助解决这个问题。以下是我的代码,用于从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");
}
}