我想添加Web通知到我的网站。我在谷歌上搜索,并找到了一些教程。如这些教程中所述,我管理显示订阅框的访问者,我也可以存储他们的数据。
主要.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;
}
软件.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
我需要一些帮助,请帮助我了解它是如何工作的。
谢谢
3条答案
按热度按时间3qpi33ja1#
请看https://web-push-book.gauntface.com/,了解Web Push的一般性介绍,其中How Push Works和Subscribing a User这一章您应该特别感兴趣。总结如下:
pushManager.subscribe
来创建订阅。juzqafwq2#
这段代码在Chrome和Mozilla中可以正常工作。
generate.php-生成VAPID密钥:
服务工人.js
index.html请求推送通知
send.php发送推送通知
zsbz8rwp3#
您必须将此代码添加到您的项目https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/有时您必须将代码添加到您已经创建的部分