Я экспериментирую с push-уведомлениями, отправленными из приложения Node.js
. Следуя некоторым учебникам и примерам, у меня теперь есть работающее мини-приложение.
То, что он делает, является очень простым, когда он загружается в браузер, уведомление запускается каждые пятнадцать секунд, и пользователь видит сообщение, появляющееся каждый раз.
Вот вопрос: как мне остановить цикл уведомлений?
На этом этапе уведомления продолжают появляться каждые пятнадцать секунд, даже когда я закрываю веб-страницу.
Для справки я поместил здесь два соответствующих файла:
index.js
const express = require('express'),
webPush = require('web-push'),
bodyParser = require('body-parser'),
path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
const privateVapIdKey = process.env.privVapIdKey,
publicVapIdKey = process.env.pubVapIdKey;
webPush.setVapidDetails(
'mailto:myemail@example.com',
publicVapIdKey,privateVapIdKey);
// Subscribe Route.
app.post('/subscribe',(req,res) => {
const subscription = req.body; // Get Push Subscription Object.
res.status(201).json({}); // Send 201. Resource created.
// Do a lot of useful things ......
.......
// Create the PayLoad.
const payload = JSON.stringify({
title:'A big title!',
........
});
// Pass Object to sendNotification loop.
const SECS = 15 * 1000;
setInterval(() => {
// Do a lot of useful things ......
.......
webPush.sendNotification(subscription,payload).catch(err => console.error(err));
}, SECS);
});
const port = 5003;
const PORT = process.env.PORT || port;
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
client.js
const publicVapIdKey = 'my-secret-3453754...pubVapIdKey';
// Chec for ServiceWorker.
if ('serviceWorker' in navigator) {
send().catch(err => console.error(err));
}
// Register ServiceWorker, Register Push, Send Push.
async function send() {
console.log("Registering ServiceWorker.");
const register = await navigator.serviceWorker.register('/worker.js', {
scope: "/"
});
console.log('ServiceWorker registered.');
console.log("Registering Push.");
//register.pushManager.uns
const subscription = await register.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(publicVapIdKey)
});
console.log('Push registered.');
console.log("Sending Push.");
await fetch('/subscribe', {
method: 'POST',
body: JSON.stringify(subscription),
headers: {
'content-type': 'application/json'
}
});
console.log('Push sent.');
}
function urlBase64ToUint8Array(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;
}
Полагаю, мне нужно добавить маршрут / unsubscribe после
ожидание получения ('/ подписаться', {
внутри client.js. Но я не уверен на 100%, и если это то, что нужно сделать, как я могу написать код.