samedi 19 janvier 2019

How to trigger service worker "Push" Web notification

How do I call my service-worker.js with just a button click? I can now push notification details which is located in my service-worker.js by clicking the push button on devtools. enter image description here

Just a click of a button is all I need, I don't know how to initiate the code with button press. I've been doing it, but I dont know what to put in my send_notification file just to trigger the notification. Help.

this is my main.js

function sendSubscriptionToBackEnd(subscription) {
    console.log(subscription);
    var subscription_parsed = JSON.parse(subscription)
    // return fetch(subscription_parsed.endpoint, {
    return fetch("send_notification.php", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            // body: JSON.stringify(subscription)
            body: subscription
        })
        .then(function (response) {
            console.log(response);
            if (!response.ok) {
                throw new Error('Bad Status code from server');
            }

            // return response.json();
        })
        .then(function (responseData) {
            console.log(responseData);
            // if (!(responseData.data && responseData.data.success)) {
            //     throw new Error('Bad response from server.');
            // }
        });
}

notifyButton.addEventListener('click', function () {
    if (isSubscribed) {
        alert("message send");
        sendSubscriptionToBackEnd(subscriptionObjectToo);
    } else {
        alert("message not send");
    }
});

I am passing the value of serviceworker.pushManager.subscribe which is this one:

{"endpoint":"https://fcm.googleapis.com/fcm/send/ezu5Ndp8ggo:APA91bFytOrF-bPdwGc4uFObqai6V7N4WFFaprwc3-CQMZdyLDzpNriFSJGsJG9TBc47x4AhgWxWkMCdBbTZiGhBy1RFv0oBQEmAUELCtpgNxGuivsjNajiXh95x3gH-NY2nyTyAtdF4","expirationTime":null,"keys":{"p256dh":"BPcqPUFomZZCNIrcbzqLWaDL-Hyc3vNuxqeMKmhbbBxJNeExd0AyZuW33gMYEEiNG9go_IyUS0VQEnDN_zj-B8E","auth":"Sn8691zwOGCd3ttXCbb47w"}}

in my notification.php but I don't know what to write in my file. Should it be a php file? or a JS file? Help

sw.js

'use strict';

self.addEventListener('push', function (event) {
    console.log('[Service Worker] Push Received.');
    console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

    const title = 'Push Codelab';
    const options = {
        body: 'Yay it works.',
        icon: 'images/icon.png',
        badge: 'images/badge.png'
    };

    event.waitUntil(self.registration.showNotification(title, options));
});

self.addEventListener('notificationclick', function (event) {
    console.log('[Service Worker] Notification click Received.');

    event.notification.close();

    event.waitUntil(
        clients.openWindow('https://developers.google.com/web/')
    );
});




Aucun commentaire:

Enregistrer un commentaire