[英]How to stop Node.JS notification flow?
I am experimenting with push-notifications sent from a Node.js
app. 我正在尝试从Node.js
应用发送的推送通知。 Following some tutorial and examples, I now have a working mini-application to start with. 在学习了一些教程和示例之后,我现在开始使用一个可运行的微型应用程序。
What it does is very basic, when it is loaded into the browser, a notification is fired every fifteen seconds and the user sees a message popping up each time. 它的功能非常基本,当将其加载到浏览器中时,每十五秒就会触发一条通知,并且用户每次都会看到一条弹出消息。
Here is the question: How should I stop the notification loop? 这是一个问题:如何停止通知循环?
At this point, the notifications keep coming every fifteen seconds even when I close the web page. 此时,即使我关闭网页,通知也会每隔15秒发送一次。
For reference I put here the two relevant files: 作为参考,我在这里放置了两个相关文件:
index.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 : 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;
}
I suppose I need to add an /unsubscribe route, after the 我想我需要在/之后添加/退订路由
await fetch('/subscribe', { 等待fetch('/ subscribe',{
inside client.js. 在client.js中。 But I am not 100% sure and if this is the thing to do, how can I write the code. 但是我不确定100%,如果要这样做,我该如何编写代码。
What you would need to do is to keep track of your setInterval
function and then use the clearInterval
function like this : 您需要做的是跟踪setInterval
函数,然后使用clearInterval
函数,如下所示:
const SECS = 15 * 1000;
const notificationLoop = setInterval(() => {
// Do a lot of useful things ......
webPush.sendNotification(subscription,payload).catch(err => console.error(err));
}, SECS);
When you want to stop it : 当您想停止它时:
clearInterval(notificationLoop);
More informations about clearInterval 有关clearInterval的更多信息
Be sure to keep the reference of your notificationLoop
to prevent it from being undefined. 确保保留您的notificationLoop
的引用,以防止未定义它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.