chrome 中不会触发浏览器通知 onclick 事件

bru*_*sli 5 javascript notifications

我正在创建浏览器通知,它在 Firefox 和 Edge 中运行良好。但由于某种原因,它在 Chrome 中不起作用。我可以看到通知,但当我单击通知时,它不会被触发。这是我的代码:

function notifyMe(text) {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        var notification = new Notification('Notification title', {               
            body: text,
            requireInteraction: true     
        });
        notification.onclick = function (event) {
            alert("clicked");
            event.preventDefault(); 
            console.log('Notification clicked.');
        } 

    }      
}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是,为什么 notificaion.onclick 在 chrome 中不会被触发?

Dem*_*ano -3

您可能正在单击关闭按钮,它不会触发单击事件,请尝试单击关闭按钮以外的任何内容,尝试使用onclose事件

function notifyMe(text) {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        var notification = new Notification('Notification title', {               
            body: text,
            requireInteraction: true     
        });
        notification.onclick = function (event) {
            alert("onClick!");
            event.preventDefault(); 
            console.log('Notification clicked.');
        } 
        notification.onclose = function (event) {
            alert("onClose!");
            event.preventDefault(); 
            console.log('Notification clicked.');
        } 
    }      
}
Run Code Online (Sandbox Code Playgroud)

或者尝试使用EventListener

function notifyMe(text) {
    if (Notification.permission !== "granted")
        Notification.requestPermission();
    else {
        var notification = new Notification('Notification title', {               
            body: text,
            requireInteraction: true     
        });
        notification.addEventListener("click", function (event) {
            alert("onClick!");
            event.preventDefault(); 
            console.log('Notification clicked.');
        } )
        notification.addEventListener("close", function (event) {
            alert("onClose!");
            event.preventDefault(); 
            console.log('Notification clicked.');
        } )

    }      
}
Run Code Online (Sandbox Code Playgroud)