Ste*_*nko 6 javascript notifications google-chrome
我使用通知API在Chrome 73上显示弹出窗口:
new Notification('', {
icon: "images/transparent.png",
image: res,
requireInteraction: true
});
notification.onclose = function () {
alert('close')
};
notification.onclick= function () {
alert('click')
};
notification.onerror= function () {
alert('error');
};
notification.onnotificationclose = function () {
alert("close")
};
Run Code Online (Sandbox Code Playgroud)
我看到这个弹出窗口:
但是问题是,如果用户单击带有箭头的图标,则会onclose被解雇,但是如果用户单击“关闭”,又名“ ???????” 按钮,不会调用任何处理程序。
我该如何处理?这是Chrome中的错误吗?
据我所知,当您像代码片段中那样使用通知 API 时,您根本无法处理通过以自定义方式单击按钮触发的事件。看起来按钮完全可见是 Chrome 特有的事情,而且它只是由设置为 引起requireInteraction的true。至少在 Firefox 和 Edge 中,该按钮根本不会显示。
作为替代方案,假设您正在使用 Service Worker,您还可以使用 Service Worker 的注册来触发通知。通过这种方式,您还可以在通知选项中使用其他属性actions,例如您可以定义应显示的按钮列表。您可以为每个按钮定义一个action按钮,并在 Service Worker 中执行相应操作。
以下代码有效,在 Chrome 73 上测试。注意浏览器兼容性。
我希望这有帮助。
索引.html
<button onclick="notifyMe()">Notify me!</button>
<script src="main.js"></script>
Run Code Online (Sandbox Code Playgroud)
main.js
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js');
}
function notifyMe() {
if (Notification.permission === 'granted') {
navigator.serviceWorker.getRegistration().then((reg) => {
var options = {
body: '<Your Notification Body>',
icon: '<Your Notification Icon>',
actions: [
{ action: 'close', title: 'Close' }
],
requireInteraction: true
};
reg.showNotification('<Your Notification Title>', options);
});
} else {
Notification.requestPermission();
}
}
Run Code Online (Sandbox Code Playgroud)
sw.js
self.addEventListener('notificationclick', (event) => {
if (event.action === 'close') {
console.log('handle close with button');
event.notification.close();
} else {
console.log('handle notification click');
}
}, false);
self.addEventListener('notificationclose', (event) => {
console.log('handle close with arrow');
}, false);
Run Code Online (Sandbox Code Playgroud)