Close / clear chrome extension notification when notification bar is open

Links: https://developer.chrome.com/apps/notifications

I use chrome.notifications.create (line identifier, object parameters, function callback); to create a chrome notification.

var id = 'list';

var options = {};
options.title = 'test';
options.iconUrl = 'notification_icon.png';
options.type = 'list';
options.message = "test";
options.buttons = [{title: 'test'}];
options.items = [{title: 'test', message:'test'}];

var createCallback = function(notificationId) { console.log(notificationId); };

chrome.notifications.create(id, options, createCallback); // returns 'list';

This creates a notification as expected. Everything is working correctly.

Then I call chrome.notification.clear (string id, function callback);

var id = 'list';

var clearCallback= function(wasCleared) { console.log(wasCleared); };

chrome.notification.clear(id, clearCallback); // returns true;

This clears the notification. Everything is working correctly.

EXCEPT does not clear the notification if the notification panel is open. This is not a serious problem in 99% of cases. Until I implemented the button code in the notification.

chrome.notifications.onButtonClicked.addListener( ); , , .

var onButtonClickedCallback = function (notificationId, buttonIndex) {
    console.log(notificationId, buttonIndex);
    if ( notificationId == 'list' ) {
        chrome.notification.clear(id, clearCallback); // returns true;
    }
}
chrome.notifications.onButtonClicked.addListener(onButtonClickedCallback); // onClick it returns 'list', 0

. , , . , , , , , .

persistence: false ( script, , , ).

- ? , . , , , .

Chrome 37.0.2019.0 canary Win8

- -, , , , . Google , HTML.

+4
2

, , , .

, . .

+5

, :

// open a window to take focus away from notification and there it will close automatically
function openTemporaryWindowToRemoveFocus() {
   var win = window.open("about:blank", "emptyWindow", "width=1, height=1, top=-500, left=-500");
   win.close();
}

chrome.notifications.clear("", function(wasCleared) {
    openTemporaryWindowToRemoveFocus()
});
+2

Source: https://habr.com/ru/post/1542461/


All Articles