如何停止Node.JS通知流?

时间:2018-06-26 18:45:09

标签: javascript node.js push-notification

我正在试验从Node.js应用发送的推送通知。在学习了一些教程和示例之后,我现在有了一个可以运行的微型应用程序。

这是非常基本的操作,将其加载到浏览器中后,每十五秒就会触发一条通知,并且用户每次都会看到一条弹出消息。

这是问题:我应如何停止通知循环?

这时,即使我关闭网页,通知也会每隔15秒发送一次。

作为参考,我在这里放置了两个相关文件:

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;
}

我想我需要在

之后添加 /取消订阅路线

等待获取('/ subscribe',{

在client.js内部。但是我不是100%知道,如果要这样做,我该如何编写代码。

1 个答案:

答案 0 :(得分:1)

您需要做的是跟踪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);

当您想停止它时:

clearInterval(notificationLoop);

有关clearInterval

的更多信息

请确保保留您的notificationLoop的引用,以免被未定义。