首页 > 解决方案 > 使用 Node.JS 的推送通知在 Google Chrome 上不起作用

问题描述

我正在学习 Node.js 并尝试使用 web-push 和 service worker 实现推送通知。它在 Firefox 中运行良好,但在 Chrome 上无法运行,是的,我已允许通知权限。我在运行 Windows 10 20H2 的 Windows 机器上。文本编辑器是 VS Code。终端是 windows powershell,我使用 npm 来运行程序。

这是我的index.js文件。

const express = require('express');
const webPush = require('web-push');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();


app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json()); 

const publicVapidKey = 'BOlVBFvhDNpLMo3dPEVZ8wDqTdT4zgHMfdMnQs0w3hR1xsiw5_qG9dgdnvUXmnGOuvFwDrGqZi6E1-ItEvj-h3o';
const privateVapidKey = 'aizehHySFENJXaE7QYAxKEqCmIcMpD4fuZM1g2Q8qfU';

webPush.setVapidDetails('mailto: test@test.com', publicVapidKey,privateVapidKey);


app.post('/subscribe', (req,res)=>{
    const subscription = req.body;

    res.status(201).json({});

    const payload = JSON.stringify({ title: 'Subscription Notification' });

    webPush.sendNotification(subscription,payload).catch(err=> console.error(err));
});

const port = 5000;
app.listen(port, ()=>console.log(`Running at port: ${port}`));

这是client.js文件。

const publicVapidKey = 'BOlVBFvhDNpLMo3dPEVZ8wDqTdT4zgHMfdMnQs0w3hR1xsiw5_qG9dgdnvUXmnGOuvFwDrGqZi6E1-ItEvj-h3o';

if('serviceWorker' in  navigator){
    send().catch(err=>console.error(err));
}

async function send(){
    console.log('Registering service worker');
    const register = await navigator.serviceWorker.register('/worker.js',{
        scope:'/'
    });
    console.log('Service worker registered');

    console.log('Registering push');
    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;
}

worker.js文件。

console.log('Service worker loaded');

self.addEventListener('push', e => {
    const data = e.data.json();
    console.log('Push received');
    self.registration.showNotification(data.title,{
        body: 'Subscription Successful',
        icon: 'https://ibb.co/P4khKPk'
    })
})

index.html文件

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset = "UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equip="X-UA_Compatible" content="ie=edge">
        <title>Push Notification using Node</title>
    </head>
    <body>
        <h1>Push Notification using Node</h1>

        <script src="client.js"></script>
    </body>
</html>

我尝试使用 Chrome 的 Web 开发人员工具查看问题。因为它显示该worker.js文件正在运行,所以我尝试手动推送到通知,然后它在第 1 行显示错误。4 在worker.js文件中。该错误显示“Uncaught SyntaxError: Unexpected token T in JSON at position 0 at worker.js:4”。请帮忙。

标签: javascriptnode.jsservice-workerweb-push

解决方案


推荐阅读