पाठ 14 / 30

Push Notifications

संदर्भ के अनुसार permission माँगें और service worker से push notifications दिखाएँ, भले ही app बंद हो।

Push Notification Flow

Push notifications को users से permission की जरूरत है। आपका server push service को messages भेजता है, जो उन्हें service worker तक deliver करता है। Users को notifications दिखाई देते हैं भले ही आपका app बंद हो।

Push permission request करें और notification दिखाएँ

Permission request करें और service worker में push events को handle करें।

// Request permission
Notification.requestPermission().then(permission => {
  console.log('Permission granted:', permission);
});

// Handle push in service worker
self.addEventListener('push', event => {
  const options = {
    body: event.data.text(),
    icon: '/icon-192.png',
    badge: '/badge-72.png'
  };
  event.waitUntil(
    self.registration.showNotification('My App', options)
  );
});

Output:

Users receive push notifications from the service worker.

एक आम गलती

हमेशा contextually push permission request करें। Page load पर तुरंत asking से high rejection rates होती हैं।