0

Is there a different way to request permission on android devices?

This works in reactjs but when i build it with ionic and make an apk it fails on android with:

Uncaught ReferenceError: Notification is not defined

On the line if (Notification.permission === "default") {.

I can test if Notification is defined but that will skip my registering on android and that is not what i want.

class NotificationService {

 subscribe() {
console.log("trying to subscribe!");

 // Ask for permission
 // Fails here on android with
// Uncaught ReferenceError: Notification is not defined

 if (Notification.permission === "default") {
   Notification.requestPermission().then((perm) => {
     if (Notification.permission === "granted") {
       regWorker().catch((err) => { console.log("error:");console.error(err); } );
     }
     else { alert("Please allow notifications."); }
   });
 }
  
 // granted
 else if (Notification.permission === "granted") {
     regWorker().catch((err) => { console.error(err); } );
 }

 // denied
 else { alert("Please allow notifications."); }

 // service worker
 async function regWorker () {
   // public key
   const publicKey = "MYKEY";
  
   // register service worker
   const reg = await navigator.serviceWorker.register("./notification-sw.js", { scope: "/" });
  console.log("Service Worker Registered...");
  await navigator.serviceWorker.ready;

   // Subscribe to push server
   const sub = await reg.pushManager.subscribe({
     userVisibleOnly: true,
     applicationServerKey: publicKey
   }).then(function(subscription) {
     // save || update db
               if (subscription) { //storing db
         } //subscription
       })
     .catch(function(e) {
       console.error('push manager subscription fail: ', e);
     });

   }
 }

 getSubscription() {
      return JSON.parse(localStorage.getItem('subscription'));
   }
}

notification-sw.js:

// Worker activation
self.addEventListener("install", (evt) => {
  self.skipWaiting();
});
 
// Listen to push
self.addEventListener("push", (evt) => {
  const data = evt.data.json();
  console.log("Push", data);
  self.registration.showNotification(data.title, {
    body: data.body,
    icon: data.icon,
    image: data.image
  });
});

Is Notification variable not used on android? What is the correct way to check Notification.permission on android? Is there some other package i require that enables me to check permissions on android before registering with regWorker?

Node64
  • 1
  • 1

0 Answers0