网页推送通知:如何使用网页推送 PHP 库?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44474960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:59:18  来源:igfitidea点击:

Web Push Notification: How to use Web Push PHP Library?

phpbrowserpush-notificationweb-push

提问by Rocky Sena

I Want to add Web Notification to my website. I searched on Google and found some tutorials about it. As described in these tutorials I manage to show subscription box to the visitors and I can store their data also.

我想向我的网站添加 Web 通知。我在谷歌上搜索并找到了一些关于它的教程。如这些教程中所述,我设法向访问者显示订阅框,并且我也可以存储他们的数据。

Main.js

主程序

'use strict';

const applicationServerPublicKey = 'BBw_opB12mBhg66Dc94m7pOlTTHb5oqFAafbhN-BNeazWk8woAcSeHdgbmQaroCYssUkqFfoHqEJyCKw';

const pushButton = document.querySelector('.js-push-btn');

let isSubscribed = false;
let swRegistration = null;

function urlB64ToUint8Array(base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/');

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}



if ('serviceWorker' in navigator && 'PushManager' in window) {
  console.log('Service Worker and Push is supported');

  navigator.serviceWorker.register('sw.js')
  .then(function(swReg) {
    console.log('Service Worker is registered', swReg);

    swRegistration = swReg;
  })
  .catch(function(error) {
    console.error('Service Worker Error', error);
  });
} else {
  console.warn('Push messaging is not supported');
  pushButton.textContent = 'Push Not Supported';
}


function initialiseUI() {
  // Set the initial subscription value
  swRegistration.pushManager.getSubscription()
  .then(function(subscription) {
    isSubscribed = !(subscription === null);

    if (isSubscribed) {
      console.log('User IS subscribed.');
    } else {
      console.log('User is NOT subscribed.');
    }

    updateBtn();
  });
}

function updateBtn() {
  if (isSubscribed) {
    pushButton.textContent = 'Disable Push Messaging';
  } else {
    pushButton.textContent = 'Enable Push Messaging';
  }

  pushButton.disabled = false;
}

sw.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 = 'Motoroids Lab';
  const options = { 
    body: 'Motoroids',
    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/')
  );
});

But now I'm stuck. No matter how much I am trying, It's hard to understand how to send push messages from my server :(

但现在我被困住了。无论我多么努力,都很难理解如何从我的服务器发送推送消息:(

I enabled SSL on my server. I installed PHP Web Push library and its dependencies on the server using composer require minishlink/web-pushcommand.

我在我的服务器上启用了 SSL。我使用composer require minishlink/web-push命令在服务器上安装了 PHP Web Push 库及其依赖项。

But what's next? I can't understand their documentation also. https://github.com/web-push-libs/web-push-php

但是接下来呢?我也无法理解他们的文档。https://github.com/web-push-libs/web-push-php

I need some help here. Please help me to understand how it works and how to it.

我需要一些帮助。请帮助我了解它是如何工作的以及如何操作。

Thank You

谢谢你

回答by Martijn

Take a look at https://web-push-book.gauntface.com/for a general introduction to Web Push. The Chapter How Push Worksand Subscribing a Usershould be particularly interesting to you. In summary:

查看https://web-push-book.gauntface.com/了解 Web Push 的一般介绍。推送如何工作订阅用户一章对您来说应该特别有趣。总之:

  • At the client side you need to create a subscription by calling pushManager.subscribe. More info here.
  • You should send this subscription to your server. For example, make an AJAX request to send the subscription (endpoint, keys.p256dh, keys.auth) to the server. More info here.
  • On the server you send a push message using the PHP Web Push library. First, you need to configure this library with your keypair. Then, you need to use the subscription (endpoint, keys.p256dh, keys.auth) to send a push message. More info here.
  • 在客户端,您需要通过调用创建订阅pushManager.subscribe。更多信息在这里
  • 您应该将此订阅发送到您的服务器。例如,发出 AJAX 请求以将订阅(端点、keys.p256dh、keys.auth)发送到服务器。更多信息在这里
  • 在服务器上,您使用 PHP Web Push 库发送推送消息。首先,您需要使用您的密钥对配置这个库。然后,您需要使用订阅(端点,keys.p256dh,keys.auth)发送推送消息。更多信息在这里

回答by Marco Abarca

you have to add this code to your project https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/sometimes you will have to add code to parts that you have already created

您必须将此代码添加到您的项目https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/有时您必须将代码添加到您已经创建的部分