首页 > 解决方案 > 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

标签: javascriptgoogle-chromegoogle-chrome-extensionnotificationsshortcut

解决方案


您可能已经想到了这一点,但对于将来偶然发现这个问题的任何人:不可能编写一个关闭Chrome 上的所有通知的扩展程序,因为任何扩展程序都无法访问用户的浏览器范围通知;中的notifications权限允许manifest.json创建和清除扩展程序创建的通知。事实上,如果允许任何扩展程序这样做,那将是侵犯隐私!

https://developer.chrome.com/apps/notifications#method-getAll

检索此应用程序或扩展程序的所有通知(强调我的。)


推荐阅读