简体   繁体   中英

Service-Worker addEventListener, how to use the event parameter?

I am now trying to make Push Notifications work with Node.js.

For that, I have followed some tutorial and documents that I could find on the net and I finally have something working using what is called Service Workers.

At this point both Push Notifications on Node.js and Service Workers are not something I am familiar with at all.

Here is my relevant code:

.....
console.log("Registering ServiceWorker.");
const register = await navigator.serviceWorker.register('/worker.js', {
    scope: "/"
});
console.log('ServiceWorker registered.');

console.log("Registering Push.");
const subscription = await register.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array(publicVapIdKey)
});
console.log('Push registered.');

console.log("Sending Push.");
await fetch('/subscribe', {
    method: 'POST',
    body: JSON.stringify(subscription),
    headers: {
        'content-type': 'application/json'
    }

});
console.log('Push sent.');
.....

and the service worker:

console.log('Service Worker Loaded.');

self.addEventListener('push', e => {
    const data = e.data.json;
    console.log('Push Received');
    self.registration.showNotification(data.title, {
        body: 'It is time to go for lunch.',
        icon: 'MyLogo.png'
    })
});

And also this, inside my index.js file:

// Subscribe Route.
app.post('/subscribe',(req,res) => {
    const subscription = req.body; // Get Push Subscription Object.
    res.status(201).json({}); // Sen 201. Resource created.
    // Create PayLoad.
    const payload = JSON.stringify({title:'This is a payload-title'});
    // Pass Object to sendNotification.
    webPush.sendNotification(subscription,payload).catch(err => console.error(err));
});

The question I want to ask is about using the second parameter of addEventListener . That is the event parameter. It seems to me that this parameter must be very important to transfer information to the Service Worker, but in my example it is totally useless and I don't know how to use it.

When I run this example in FireFox or Chrome I can see this kind of notification:

在此处输入图片说明

One can see "undefined" displayed on the screenshot. That is what comes from data.title (coming from the e parameter). How should I change the code to see something else than "undefined" displayed? I want to be able to make the change ouside of this block of course:

self.addEventListener('push', e => {...})

I have already tried to set some "title" field, where I thought could be a solution, but nothing worked. I am obviously not doing the right thing.

In other words, more generally speaking; what I want to know is "How to use the event parameter of addEventListener". Even a very basic example(of how to change my code for that) would be very much appreciated.

According to Push API specs e.data is an instance of PushMessageData . You see read more here for its interface. You code should be:

self.addEventListener('push', function(e) {
    let data = {};

    if (e.data) {
        // IMPORTANT:
        // The following line does not use "e.data.json",
        // but "e.data.json()" !!!!!
        data = e.data.json();
    }

    self.registration.showNotification(data.title, {
        body: 'It is time to go for lunch.',
        icon: 'MyLogo.png'
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM