Chrome扩展程序开发:自动关闭通知框

7

在完成某些操作后,我运行了以下代码:

var notification = webkitNotifications.createNotification(
   'icon.png',  // icon url - can be relative
  'Done!',  // notification title
  'Just updated your list!'  // notification body text
   );
  notification.show();

当然,它会在用户屏幕上弹出通知。

有没有一种方法可以定时这个通知,让它在X秒后自动关闭?

谢谢! R


请查看此答案以获取详细描述:https://dev59.com/upXfa4cB1Zd3GeqPdlqJ#51572172 - IRSHAD
5个回答

16

您可以使用notification.cancel();


我喜欢 notification.cancel();,因为它可以从创建通知的同一函数中调用。 - smfoote
谢谢!完全符合我的预期! - Ryan
API 可能会有更新,现在你应该使用 notification.close()。 - William

9
var notification = webkitNotifications.createNotification('images/icon-48x48.png',"This is       Title","Biswarup Adhikari Notification");
notification.show();
setTimeout(function(){
notification.cancel();
},2000);

Chrome通知将在2000毫秒或2秒后自动关闭。


3
您可以在通知的HTML页面内调用window.close()来关闭通知。
要在特定时间关闭,可以调用类似setTimeout( function () { window.close(); }, timeInMicroseconds);的方法。

谢谢你!太棒了! - Ryan

0
function show(title, message, icon) {
try {
    icon = icon || 'src/img/icons/icon48.png';
    var self = this;
    var isClosed = false;
    var notificationId = "posting_" + Math.random();

    chrome.notifications.create(notificationId, {
        type: "basic",
        title: title + "!",
        message: message,
        iconUrl: icon
    }, function (nId) {
    });

    setTimeout(function () {
        if (!isClosed)
            chrome.notifications.clear(notificationId, function (wasCleared) {
            });
    }, 3000);
} catch (e) {
    alert(e.message);
}

}

好的,当我创建通知时,请记住ID notificationId 并使用 setTimeout 清除此 ID。


请解释您所做的更改及其原因。 - timbmg

-1
//Use requireInternaction and set it to true for notification to not to auto-hide.

function showNotification() {
    var options = {
        body: 'The Subtitles will Go Here',
        requireInteraction: true
    };

    if (window.Notification && Notification.permission !== "denied") {
       Notification.requestPermission(function (status) {  // status is "granted", if accepted by user

var n = new Notification('Title', options);
        });
     }

   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接