Unable to store web notifications received in service worker in indexDB

余生颓废 提交于 2019-12-13 03:43:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!