我是谷歌Chrome推送通知的新手,我只是在这里阅读一些问题和答案,在stackoverflow上,我已经用这个简单的推送通知javascript结束了。
navigator.serviceWorker.register('sw.js');
function notify() {
Notification.requestPermission(function(result) {
if (result === 'granted') {
navigator.serviceWorker.ready.then(function(registration) {
registration.showNotification('test notification', {
body: 'Hey I am test!',
icon: 'image.png',
});
});
}
});
}
它只是简单的通知,但我需要在点击通知后打开与其他网页的新窗口。
我知道这是可能的,但我找不到使用" serviceWorker"语法。
请帮忙。感谢。
答案 0 :(得分:24)
我猜你是在Service Worker上下文中,因为那是收到推送通知的地方。所以你有self
对象来添加一个事件监听器,这会对点击通知作出反应。
self.addEventListener('notificationclick', function(event) {
let url = 'https://example.com/some-path/';
event.notification.close(); // Android needs explicit close.
event.waitUntil(
clients.matchAll({type: 'window'}).then( windowClients => {
// Check if there is already a window/tab open with the target URL
for (var i = 0; i < windowClients.length; i++) {
var client = windowClients[i];
// If so, just focus it.
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
// If not, then open the target URL in a new window/tab.
if (clients.openWindow) {
return clients.openWindow(url);
}
})
);
});
答案 1 :(得分:3)
我也在寻找解决方案,答案很简单,但是没有医生说清楚。您需要将“ click_action” =“您的网址”放入通知json中。这是一个示例:
notification: {
title: "Come",
icon: '../../../../assets/logo.png',
vibrate: [300,100,400,100,400,100,400],
body: "some text",
click_action : "your link"
}
希望有帮助。
答案 2 :(得分:2)
如果您想要使用从FCM推送通知或任何其他网络推送通知收到的动态网址打开网站,那么
以下是用于FCM推送通知的服务工作者的例子
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = payload.data.title; //or payload.notification or whatever your payload is
var notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
data: { url:payload.data.click_action }, //the url which we gonna use later
actions: [{action: "open_url", title: "Read Now"}]
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
并使用以下代码处理点击事件
self.addEventListener('notificationclick', function(event) {
switch(event.action){
case 'open_url':
clients.openWindow(event.notification.data.url); //which we got from above
break;
case 'any_other_action':
clients.openWindow("https://www.example.com");
break;
}
}
, false);
希望它有所帮助!
答案 3 :(得分:1)
以下是两个可以帮助您的网站。
您必须首先点击通知,然后才能附加您想要打开的网址
https://groups.google.com/a/chromium.org/forum/m/#!topic/chromium-extensions/nevc6nRpAlQ
https://developer.chrome.com/extensions/notifications#event-onClicked
希望有所帮助:)
答案 4 :(得分:0)
{
"notification": {
"title": "Hey there",
"body": "Subscribe to might ghost hack youtube channel",
"click_action" : "http://localhost:4200"
},
"to":"YOUR_TOKEN"
}
这对我有用
"@angular/fire": "^6.1.5",
"firebase": "^7.0 || ^8.0"