Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/404.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/38.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何停止Node.JS通知流?_Javascript_Node.js_Push Notification - Fatal编程技术网

Javascript 如何停止Node.JS通知流?

Javascript 如何停止Node.JS通知流?,javascript,node.js,push-notification,Javascript,Node.js,Push Notification,我正在尝试从Node.js应用程序发送推送通知。根据一些教程和示例,我现在有了一个可以工作的迷你应用程序 它所做的是非常基本的,当它被加载到浏览器中时,每15秒就会触发一次通知,用户每次都会看到弹出的消息 问题是:如何停止通知循环? 此时,即使在我关闭网页时,通知也会每隔15秒发出一次 为了便于参考,我在这里放了两个相关文件: index.js: const express = require('express'), webPush = require('web-push'),

我正在尝试从
Node.js
应用程序发送推送通知。根据一些教程和示例,我现在有了一个可以工作的迷你应用程序

它所做的是非常基本的,当它被加载到浏览器中时,每15秒就会触发一次通知,用户每次都会看到弹出的消息

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

此时,即使在我关闭网页时,通知也会每隔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 }`));
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;
}
client.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 }`));
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;
}
const publivapidkey='my-secret-3453754…publivapidkey';
//服务工人的Chec。
if(导航器中的“serviceWorker”){
send().catch(err=>console.error(err));
}
//注册ServiceWorker、注册推送、发送推送。
异步函数send(){
log(“注册ServiceWorker”);
const register=wait navigator.serviceworner.register('/worker.js'{
范围:“/”
});
日志('ServiceWorker registered');
log(“注册推送”);
//register.pushManager.uns
const subscription=wait register.pushManager.subscripte({
userVisibleOnly:true,
applicationServerKey:urlBase64ToUint8Array(publicVapIdKey)
});
log('Push registered');
日志(“发送推送”);
等待获取(“/subscribe”{
方法:“POST”,
正文:JSON.stringify(订阅),
标题:{
“内容类型”:“应用程序/json”
}
});
console.log('Push-sent');
}
函数urlBase64ToUint8Array(base64String){
常量填充='='.repeat((4-base64String.length%4)%4);
常量base64=(base64String+填充)
.替换(/\-/g,“+”)
.替换(/_/g,“/”);
const rawData=window.atob(base64);
const outputArray=新的Uint8Array(rawData.length);
for(设i=0;i
我想我需要在

等待获取('/subscribe',{


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

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


请确保保留您的
通知循环的引用
,以防止其未定义。

您的建议非常有趣,但您提到的页面涉及客户端工作的内容(给出的示例是一个计时器,带有停止按钮)。在我的情况下,通知是从服务器发出的。情况有所不同。阅读了相当多的内容后,我认为我需要在现有的订阅功能之外添加一些取消订阅功能。但我不确定如何做。