如何通过单击按钮触发服务人员“推送” Web通知

时间:2019-01-19 10:15:07

标签: javascript php web push-notification service-worker

如何仅需单击一下即可调用我的service-worker.js?现在,我可以通过单击devtools上的按钮来推送位于service-worker.js中的通知详细信息。 enter image description here

仅需单击一个按钮,我不知道如何通过按下按钮来启动代码。我一直在做,但是我不知道要触发通知是在send_notification文件中添加什么。帮助。

这是我的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");
    }
});

我正在传递serviceworker.pushManager.subscribe的值,这就是这个值:

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

在我的notification.php中,但是我不知道该写什么。应该是一个php文件吗?或JS文件?帮助

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/')
    );
});

0 个答案:

没有答案