我想在我的网站上添加网络通知。我在Google上搜索并找到了一些关于它的教程。如这些教程中所述,我设法向访问者显示订阅框,我也可以存储他们的数据。
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
'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/')
);
});
但现在我被卡住了。无论我尝试多少,都很难理解如何从我的服务器发送推送消息:(
我在服务器上启用了SSL。我使用composer require minishlink/web-push
命令在服务器上安装了PHP Web Push库及其依赖项。
但下一步是什么?我也无法理解他们的文档。 https://github.com/web-push-libs/web-push-php
我需要一些帮助。请帮助我了解它是如何工作的以及如何工作。
谢谢
答案 0 :(得分:12)
Take a look at https://web-push-book.gauntface.com/ for a general introduction to Web Push. The Chapter How Push Works and Subscribing a User should be particularly interesting to you. In summary:
pushManager.subscribe
. More info here.答案 1 :(得分:-1)
您必须将此代码添加到项目https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/,有时您必须将代码添加到已创建的部分