Google Chrome扩展程序可在用户点击后关闭通知

时间:2016-03-23 11:45:37

标签: javascript google-chrome-extension

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);
        }    
    });
}

4 个答案:

答案 0 :(得分:2)

首先创建通知并为其提供一个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);

现在,当您点击通知时,它会关闭。

答案 1 :(得分:1)

您可以使用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演示

答案 2 :(得分:1)

此功能目前仅在测试版渠道中实施,而不是在最新版本的Chrome中实施。有关详细信息,请参阅here

实施后,您可以使用requireInteraction : True之类的:

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

实现这一点。

答案 3 :(得分:0)

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);