为啥我没有弹出推送通知?
Posted
技术标签:
【中文标题】为啥我没有弹出推送通知?【英文标题】:Why don't I get the push notification pop up?为什么我没有弹出推送通知? 【发布时间】:2017-10-24 00:52:28 【问题描述】:我有以下代码用于处理和订阅在端口4000
上运行的前端推送通知:
var endpoint;
var key;
var authSecret;
// We need to convert the VAPID key to a base64 string when we subscribe
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;
function determineAppServerKey()
var vapidPublicKey = 'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY';
return urlBase64ToUint8Array(vapidPublicKey);
export default function registerServiceWorker()
if('serviceWorker' in navigator)
navigator.serviceWorker.register(`$process.env.PUBLIC_URL\sw.js`).then(function(register)
console.log("worked", register)
return register.pushManager.getSubscription()
.then(function(subscription)
if (subscription)
// We already have a subscription, let's not add them again
return;
return register.pushManager.subscribe(
userVisibleOnly: true,
applicationServerKey: determineAppServerKey()
)
.then(function(subscription)
var rawKey = subscription.getKey ? subscription.getKey('p256dh') : '';
key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : '';
var rawAuthSecret = subscription.getKey ? subscription.getKey('auth') : '';
authSecret = rawAuthSecret ?
btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) : '';
endpoint = subscription.endpoint;
alert("came here")
return fetch('http://localhost:3111/register',
method: 'post',
headers: new Headers(
'content-type': 'application/json'
),
body: JSON.stringify(
endpoint: subscription.endpoint,
key: key,
authSecret: authSecret,
),
)
);
);
).catch(function(err)
console.log("Error",err)
)
服务器代码如下所示:
const webpush = require('web-push');
const express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
const app = express();
// Express setup
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( // to support URL-encoded bodies
extended: true
));
function saveRegistrationDetails(endpoint, key, authSecret)
// Save the users details in a DB
webpush.setVapidDetails(
'mailto:contact@deanhume.com',
'BAyb_WgaR0L0pODaR7wWkxJi__tWbM1MPBymyRDFEGjtDCWeRYS9EF7yGoCHLdHJi6hikYdg4MuYaK0XoD0qnoY',
'p6YVD7t8HkABoez1CvVJ5bl7BnEdKUu5bSyVjyxMBh0'
);
// Home page
app.get('/', function (req, res)
res.sendFile(path.join(__dirname + '/index.html'));
);
// Article page
app.get('/article', function (req, res)
res.sendFile(path.join(__dirname + '/article.html'));
);
// Register the user
app.post('/register', function (req, res)
var endpoint = req.body.endpoint;
var authSecret = req.body.authSecret;
var key = req.body.key;
// Store the users registration details
saveRegistrationDetails(endpoint, key, authSecret);
const pushSubscription =
endpoint: req.body.endpoint,
keys:
auth: authSecret,
p256dh: key
;
var body = 'Thank you for registering';
var iconUrl = 'https://raw.githubusercontent.com/deanhume/progressive-web-apps-book/master/chapter-6/push-notifications/public/images/homescreen.png';
webpush.sendNotification(pushSubscription,
JSON.stringify(
msg: body,
url: 'https://localhost:3111',
icon: iconUrl,
type: 'register'
))
.then(result =>
console.log("came here ")
console.log(result);
res.sendStatus(201);
)
.catch(err =>
console.log(err);
);
);
// The server
app.listen(3111, function ()
console.log('Example app listening on port 3111!')
);
服务器在3111
上运行。当我导航到4000
端口时,我可以看到允许/阻止弹出窗口出现,如果我允许,我希望服务器发送Thank you for registering
消息,就像我在服务器中所做的那样。但是,Thank you for registering
弹出窗口没有出现,并且控制台中没有错误。
注意:我通过使用 chrome-extension 启用 CORS 来访问 3111
。
【问题讨论】:
by enabling CORS
- 你在哪里启用 CORS?我在您发布的代码中的任何地方都没有提到 cors 或相关的访问控制允许标头
@JaromandaX:使用 chrome-extension,我已经更新了问题
哦,所以你还没有启用 CORS,你已经绕过了 CORS
@JaromandaX:那我现在该怎么办?
哦,我不知道,我只是更正您声称您已“启用 CORS”的说法 - 浏览器开发人员工具控制台/网络选项卡可能会提供一些错误信息供您使用
【参考方案1】:
我认为这可能取决于您的服务器,因为我家里有一个 python 服务器,当我使用通知 api 时它不会通知,除非我在 https 站点上。如果这不是问题,那么我会假设存在代码错误,但我相信您可以使用广播频道和 xhr,例如:let b = new BroadcastChannel;b.onmessage(function()XmlHTTPRequest('POST', Data: "yes"); )
并使用 xhr 推送通知。
【讨论】:
以上是关于为啥我没有弹出推送通知?的主要内容,如果未能解决你的问题,请参考以下文章