我是 Google 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”语法的示例。
请帮忙。谢谢。
最佳答案
我猜您在 Service Worker 上下文中,因为这是接收推送通知的地方。所以你有 self
对象来添加一个事件监听器,它会对通知的点击使用react。
(将此代码放在您的 sw.js
文件中,这是您的 Service Worker 脚本。)
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);
}
})
);
});
关于javascript - Chrome推送通知-点击后如何打开URL地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39418545/