【发布时间】:2018-03-18 03:04:54
【问题描述】:
我正在按照创建网络推送通知网站的指南进行操作,但我被这一步卡住了,你们能帮帮我吗?
我正在从 notification.php 获取通知数据(正文、图标、url 等),并且通知显示完美。当我尝试将 URL 传递给第二个事件侦听器时出现问题 - 用于通知点击。
如何在第一个事件侦听器中获取 URL,然后在第二个事件侦听器中使用它,而无需第二次获取?
.then(function(response) {
var notif_url = response.notif_url;
它在这里工作,我想将 notif_url 传递给这个事件监听器:
self.addEventListener('notificationclick', function(event, url) {
我的 serviceworker.js:
self.addEventListener('push', function(event) {
// const analyticsPromise = pushReceivedTracking();
const pushInfoPromise = fetch('notification.php')
.then(function(response) {
return response.json();
})
.then(function(response) {
var notif_url = response.notif_url;
console.log(notif_url);
return self.registration.showNotification(response.notif_title, {
"body": response.notif_body,
"icon": response.notif_icon,
"image": response.notif_image,
"badge": response.notif_badge,
"vibrate": response.notif_vibrate,
"sound": response.notif_sound,
"dir": response.notif_dir,
"tag": response.notif_tag,
"data": response.notif_data,
"requireInteraction": true,
"renotify": response.notif_renotify,
"silent": false,
// "actions": response.notif_actions,
// "timestamp": response.notif_timestamp
});
});
const promiseChain = Promise.all([
// analyticsPromise,
pushInfoPromise
]);
event.waitUntil(promiseChain);
});
self.addEventListener('notificationclick', function(event, url) {
const pushInfoPromise = fetch('notification.php')
.then(function(response) {
url = response.notif_url;
})
event.notification.close();
event.waitUntil(
clients.openWindow(url)
);
});
提前谢谢你!
【问题讨论】:
-
为什么不把notif_url保存为类级变量并在notificationclick事件中使用呢?
-
感谢您的建议。我必须从 fetch('notification.php') 获取 URL - 在第一个事件侦听器中,然后将参数传递给第二个侦听器。
标签: javascript node.js web push