用户点击后关闭通知的Google Chrome扩展

Google Chrome extension to close notification after user click

本文关键字:Google Chrome 扩展 通知 用户      更新时间:2023-09-26

Chrome扩展运行良好。我的问题是通知在7秒内关闭。我希望用户单击以关闭通知。

function engine(){
    var latestId;
    var ids;
    var messages = [];
    var newmessage = [];
    $.get('http://localhost/site/json.php',function (data){
        var json = $.parseJSON(data);
        messages = json;
        ids = json[0].id;
        if(latestId == ids){
            //no update
        }else if(latestId === undefined){
            var run = {
                type: "basic",
                title: "Title",
                message: "Some message",
                iconUrl : "icon.png",
            };
            chrome.notifications.create(run);
        }    
    });
}

首先创建通知,并为其提供notificationID参数以便稍后关闭。

var notification = {
    type:"basic",
    title:"News From Us!",
    message:"Google Chrome Updated to v50!",
    iconUrl:"assets/images/icon.png"
};
chrome.notifications.create("notfyId",notification);

点击通知后,您可以使用其id(即"notfyId")关闭通知

function forwardNotfy(){
    chrome.notifications.clear("notfyId");
    window.open(url); //optional
 }
 chrome.notifications.onClicked.addListener(forwardNotfy);

现在,当您单击通知时,它将关闭。

此功能目前仅在测试版通道中实现,而未在最新版本的chrome中实现。请参阅此处了解详细信息。

当它实现时,您将能够使用requireInteraction : True,如:

var run = {
    type: "basic",
    title: "Title",
    message: "Some message",
    iconUrl : "icon.png",
    requireInteraction : True,
}

以实现这一点。

您可以使用notification.close();:

setTimeout(function() {
    notification.close();
}, 2000);

演示:

// request permission on page load
document.addEventListener('DOMContentLoaded', function () {
  if (Notification.permission !== "granted")
    Notification.requestPermission();
});
function notifyMe() {
  if (!Notification) {
    alert('Desktop notifications not available in your browser. Try Chromium.'); 
    return;
  }
  if (Notification.permission !== "granted")
    Notification.requestPermission();
  else {
    var notification = new Notification('Notification title', {
      icon: 'http://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png',
      body: "Hey there! You've been notified!x",
    });
    notification.onclick = function () {
      window.open("http://stackoverflow.com/a/13328397/1269037");      
    };
    
    setTimeout(function() {
    notification.close();
}, 2000);
  }
}
<button onclick="notifyMe()">
  Notify me!
</button>

JSBin演示

notification.close()用于关闭任何通知。

有关更多信息,请参阅以下代码-

创建通知:

var notification = new Notification('OnlineOfferPrice', {
    icon: 'icon.png',
    body: "Test Message",
});

如果您想在通知时执行操作,请使用以下代码。在您的业务逻辑之后,它将自动关闭-

notification.onclick = function () { 
    //write your business logic here.
    notification.close();
};

如果通知没有点击,并且您想在6秒后自动关闭它-

setTimeout(function() { notification.close(); }, 6000);