samedi 17 mars 2018

Use fetched data with 2 event listeners

I'm following a guide for creating a website for web push notifications, but I'm stuck with this step, could you guys help me?

I'm getting notification data (body, icon, url etc.) from notification.php and the notification is displaying perfectly. The problem comes when I try to pass the URL to the second event listener - for the notification click.

How can I get the URL in the first event listener and then use it in the second, without second fetch?

.then(function(response) {
var notif_url = response.notif_url;

It's working here, I want to pass notif_url to this event listener:

self.addEventListener('notificationclick', function(event, url) {

My serviceworker.js:

self.addEventListener('push', function(event) {
// const analyticsPromise = pushReceivedTracking();
const pushInfoPromise = fetch('notification.php')
.then(function(response) {
  return response.json();
})
.then(function(response) {
var notif_url = response.notif_url;
console.log(notif_url);
  return self.registration.showNotification(response.notif_title, {
    "body": response.notif_body,
    "icon": response.notif_icon,
    "image": response.notif_image,
    "badge": response.notif_badge,
    "vibrate": response.notif_vibrate,
    "sound": response.notif_sound,
    "dir": response.notif_dir,
    "tag": response.notif_tag,
    "data": response.notif_data,
    "requireInteraction": true,
    "renotify": response.notif_renotify,
    "silent": false,
    // "actions": response.notif_actions,
    // "timestamp": response.notif_timestamp
  });
});

const promiseChain = Promise.all([
// analyticsPromise,
pushInfoPromise
]);

event.waitUntil(promiseChain);
});

self.addEventListener('notificationclick', function(event, url) {
const pushInfoPromise = fetch('notification.php')
.then(function(response) {
  url = response.notif_url;
})

event.notification.close();
event.waitUntil(
clients.openWindow(url)
);
});

Thank you in advance!




Aucun commentaire:

Enregistrer un commentaire