我正在遵循创建网络推送通知网站的指南,但我坚持这一步,你们可以帮帮我吗?
我从notification.php获取通知数据(正文,图标,网址等),通知显示完美。当我尝试将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)
);
});
提前谢谢!
答案 0 :(得分:0)
我修改了您的serviceworker.js
以删除第二次抓取。只需在showNotification
中再添加一个参数,您就可以在notificationclick
// 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,
"notifi_url": notif_url,
"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) {
//if you already have url as separate parameter here then no need to pass it in showNotification
url = event.notifi_url
event.notification.close();
event.waitUntil(
clients.openWindow(url)
);
});