Som
Som

Reputation: 960

Web Push - Placing service worker

From here https://developers.google.com/web/fundamentals/getting-started/primers/service-workers

  1. If the service worker is at the root of the domain, this means that the service worker's scope will be the entire origin.
  2. But If we register the service worker file at /example/sw.js, then the service worker would only see fetch events for pages whose URL starts with /example/ (i.e. /example/page1/, /example/page2/).

Second point mentions only fetch won't work at / (root or other than example) if I place the service worker at /example/.

But subscription (generation of sub object) itself not getting generated if the service worker is at /example/ and if the web page is at / (root or other than example), which the doc clearly doesn't explain.

Please let me know, if even the generation of subscription (pushManager.getSubscription) in the service worker itself won't happen.

PS: I have tried it on Chrome 54.0.2840.100 Ubuntu 16.04 LTS

Upvotes: 1

Views: 842

Answers (1)

Sakshi Nagpal
Sakshi Nagpal

Reputation: 1033

Generation of subscription object does not depend on service worker scope. You can do it any where

Eg. permission.js

export function allowNotifications(scope){
  if (navigator.serviceWorker && Notification){
    if( Notification.permission !== "granted") {
      navigator.serviceWorker.ready.then(function(reg) {
        subscribe(reg);
      });
    }
  }
}

function subscribe(reg) {
     reg.pushManager.subscribe({userVisibleOnly: true}).then(function(pushSubscription) {
          bindUserToDevice(JSON.stringify(pushSubscription));
     }, function (err) {
        console.log('error');
      });
}

export function bindUserToDevice(subscriptionObj) {

  // received subsciption object should be send to backend to bind the device for pushes
  var data = {
    type: 'POST',
    url : '/bind',
    body: subscriptionObj,
  };
  fetch('/bind', data);

}

allowNotifications function can be called from anywhere. Only the service worker file should be present on root which should have push event

 global.addEventListener('push', function(event) {
    var pushObj = event.data.json();
    var pushData = pushObj.data;

    var title = pushData && pushData.title;
    var body = pushData && pushData.body;
    var icon = '/img/logo.png';

    event.waitUntil(global.registration.showNotification(title, {
        body: body,
        icon: icon,
        data:pushData
    }));
});

Upvotes: 1

Related Questions