Zahra
Zahra

Reputation: 101

I can't store data from setBackgroundMessageHandler

I'm using firebase for pushing notification. When I get the notification in the background, I get data. I want to save this data in the local storage, but I get this error

TypeError: Cannot read property 'setItem' of undefined

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
firebase.initializeApp({
  messagingSenderId: '628214501041'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  var notificationTitle = 'Background Message Title';
  var notificationOptions = {
    body: 'Background Message body.',
  };
  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
self.addEventListener('push', function (event) {
  var pushData = event.data.json();
  try {
    if(self.window.localStorage){
      self.localStorage.setItem('notificationData' , JSON.stringify(pushData) ) ;
    // }
  }
 catch (err) {
    console.log('Push error happened:', err);
  }
});

Upvotes: 1

Views: 1776

Answers (2)

Dnl
Dnl

Reputation: 601

Well, you can't access the local storage or the session storage from your service worker because it have no access to the DOM.

You should use CacheAPI

Or for persisting data and access it from your service worker and window instance use:

IndexedDB

This is in the lifecyle of your service worker and can also be accessed by the window object.

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 599011

The self variable you're using in your code is not something that is defined by default.

But from your code, you're probably looking for:

if(self.window.localStorage) {
  self.window.localStorage.setItem('notificationData' , JSON.stringify(pushData) ) ;
}

So the change there is using self.window.localStorage, instead of self.localStorage in the second line.

Upvotes: 1

Related Questions