Search code examples
push-notificationweb-workerservice-worker

Marking push notifications as read by making post request from service worker


I implemented push notifications using service worker. When user clicks on the notification I want to make the notification as "read" in my database. I have written an API call to mark a notification as "read". How to make this call from the service worker. My API call is in my application js file.


Solution

  • I found the solution. We can directly call our API using "fetch" event from the service worker. And set the "credentials" option in fetch as "include", if you want to include the cookies in the request

     fetch(url, { 
                    method: 'post',
                    credentials: 'include',
                    body: JSON.stringify({"event_id": <event-id-value>})  
                  })
                  .then(function (data) {
                    //console.log('Request succeeded with JSON response', data);  
                  })  
                  .catch(function (error) {  
                    //console.log('Request failed', error);  
                  });