通知 API onclose 事件未触发

问题描述 投票:0回答:1

我正在尝试从使用通知 API 创建的通知中启动应用程序中的某些行为。我这样做取得了一些成功,但是无论用户单击通知还是通过单击 X 关闭通知,以及无论出于何种原因,无论浏览器如何,onclose 事件都不会触发,我们都需要相同的行为。这是一个 React 应用程序,代码如下所示:

`async function showNotification() {
    if (Notification.permission !== "granted") {
        await Notification.requestPermission()
    }

    if (Notification.permission === "granted") { 
        const notification = new Notification('New Camera Alerts', { 
            body: 'There are new notifications to review in the Notification Panel', 
            icon: `${logo}`, 
            requireInteraction: true // this makes the dialog stay open until someone clicks it 
        }) 

        const testEvent = (event: Event) => { 
            event.preventDefault() 
            // more lines of code here with what should happen when the 
            // notification is clicked/closed 
        }

        notification.onclick = (event) => testEvent (event) 
        notification.onclose = (event) => testEvent (event) 
    } 

}`

我尝试的是将相同的函数调用分配给单击和关闭处理程序。我期望这两个操作具有相同的行为。实际发生的情况是 close 事件根本不会被触发。

reactjs notifications
1个回答
0
投票

问题出在原生通知上。

close
事件仅在点击“关闭”按钮关闭通知时触发,但当隐藏右上角带叉(x)的通知、超时隐藏(原生约为 6 秒)或滑动通知(触摸屏)时不会触发事件).

关闭按钮通常不会显示,这就是为什么它看起来像

close
事件永远不会被触发。所以你必须使用特殊选项
requireInteraction: true
。然后就不会出现超时、“关闭”按钮和功能性
onclose
事件:)

示例:

let n = new Notification('this is my notification with close', {requireInteraction: true});
n.addEventListener('close', ()=>{
    alert('onclose event triggered!');
});
© www.soinside.com 2019 - 2024. All rights reserved.