Search code examples
javascriptfetch-apiservice-workerchrome-gcm

Update dynamic data in service-worker.js


I have the below data coming in form of array from a url.

[{"title":"hey hi","body":"hello","url":"https://simple-push-demo.appspot.com/","tag":"new"}]

service-worker.js it has the above url in fetch()

 'use strict';

console.log('Started', self);
self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log('Installed new', event);
});
self.addEventListener('activate', function(event) {
  console.log('Activatednew', event);
});

self.addEventListener('push', function(event) {
    try{
  console.log('Push message', event);
  var ev = event;

  //sample
  return fetch("http://localhost/push-notifications-master/app/json.php").then(function(ev,response) {
    response = JSON.parse(JSON.stringify(response));
    return response;
}).then(function(ev,j) {
    // Yay, `j` is a JavaScript object
    console.log("j", j);
 for(var i in j) {
    var _title = j[i].title;
    var _body = j[i].body;
    var _tag = j[i].tag;
     console.log("_body", _body);
    }
    ev.waitUntil(
        self.registration.showNotification("push title", {
      body: _body,
      icon: 'images/icon.png',
      tag: _tag
    }));    
});

return Promise.all(response);

    }
    catch(e){console.log("e", e)}
});

I am trying to see the above array data coming from that particular url in console.log("j",j);. but it shows undefined. How can i get dymanic data in sw.js Please Guide.


Solution

  • In your addEventListener('push' .... method, I think it might be better to wait for a response before parsing it.

    Also, to be checked, but your php request should be in https (not checked by myself, but my request are on https).

    Here how I do this :

    event.waitUntil(
        fetch('YOUR PHP URL').then(function(response) {
            if (response.status !== 200) {
                console.log('Problem. Status Code: ' + response.status);  
                throw new Error();  
            }
            // Examine the text in the response  
            return response.json().then(function(data) { 
                if (data.error || !data.notification) {
                    console.error('The API returned an error.', data.error);  
                    throw new Error();  
                }
                var title = data.notification[0].title;  
                var body = data.notification[0].body;  
                var icon = data.notification[0].icon;  
                var notificationTag = data.notification[0].tag;
                return self.registration.showNotification(title, {body: body,icon:icon, tag: notificationTag});
            });
        })
    );
    

    The json :

    {"notification" : [{"title":"TITLE","body":"BODY","icon":"URL TO ICON","tag":"TAG"}]}
    

    Hope it can be useful.