问题
I am using Firebase cloud messaging. I am using the below sample link. https://github.com/firebase/quickstart-js
Notifications are received. I want to store notifications in indexDB in service worker.
var setupDone = false;
var storage = {
setup: function() {
return new Promise(function(resolve, reject) {
var request = indexedDB.open(notificationdb, 1);
request.onsuccess = function (e) {
setupDone = true;
var db = e.target.result;
storage.db = db;
resolve();
};
request.onupgradeneeded = function (e) {
storage.db = e.target.result;
if (storage.db.objectStoreNames.contains('notifications')) {
storage.db.deleteObjectStore('notifications');
}
storage.db.createObjectStore('notifications', {
keyPath: '_id'
});
};
});
},
transaction: function (mode) {
var trans = storage.db.transaction('notifications', mode);
return trans.objectStore('notifications');
},
add: function (notification) {
return new Promise(function(resolve, reject) {
var request =
storage.transaction('readwrite').put(notification);
request.onsuccess = function () {
resolve(notification);
};
request.onerror = function() {
reject();
};
});
}
};
messaging.setBackgroundMessageHandler(function(payload) {
var notification = payload.notification;
var data = {};
data.title = notification.title;
data.message = notification.body;
data._id = getUniqueId();
data.time = Date.now();
if (!setupDone) {
storage.setup().then(function() {
storage.add(data);
});
} else {
storage.add(data);
}
return
self.registration.showNotification(notification.title,notification.body);
});
But it is not stored in indexDB. Database is created. But data is not stored. Please help if anything is wrong here.
来源:https://stackoverflow.com/questions/45451648/unable-to-store-web-notifications-received-in-service-worker-in-indexdb