Skip to content

Creating Chrome Extension to Dismiss Notifications via Keyboard Shortcut

I’m new to Chrome extension development. I am currently looking to make a Chrome extension to dismiss notifications. I want the extension to be activated once via shortcut keys.

Before looking at the code below, I want to let it be known that the alert does show up… but the Chrome Extensions page shows the error:

“Error in event handler for commands.onCommand: TypeError: Cannot read property ‘getAll’ of undefined”

on the line:

chrome.notifications.getAll((items) => {

The chrome.notifications object is somehow undefined, so it seems that Chrome thinks that there are no current notifications being displayed…which is strange because there indeed are, as the image shows.

Would anyone please help by shedding some light on this situation?


manifest.json:
{
"name": "ClearAll",
"version": "1.0",
"description": "Clear notifications!",
"background": {
  "scripts": ["background.js"],
  "persistent": false
},

"commands": {
  "clear": {
    "suggested_key":{
      "default": "Alt+Shift+S" 
    },
    "description": "Executes clear"
 }
},
"manifest_version": 2
}

background.js:

chrome.commands.onCommand.addListener(function(command) {
    if (command == 'clear') {
      alert("testing");
      chrome.notifications.getAll((items) => {
        if (items) 
          for (let key in items) 
            chrome.notifications.clear(key);
      });
    }
});

Error:

Image: Cannot read property 'getAll' of undefined error

Answer

You need to add the notifications permission to your manifest

{
    "name": "ClearAll",
    "permissions": ["notifications"],
    .......
}