Search code examples
google-chrome-extension

How to request permission with chrome.notifications in chrome extension


I would like to use chrome.notifications in my extension. When I load-unpacked my extension, I noticed that just by going to the extension page, I was already granted permission to use notifications.

Shouldn't there be a prompt asking for the user's permission to use notifications? My plan is to give users the option to allow or disallow notifications for the extension. This issue affects my plan to include a button that will ask users for permission for notifications.

manifest.json

{
  "manifest_version": 2,
  "name": "",
  "version": "",
  "description": "",
  "icons": {
    "16": "",
    "48": "",
    "128": ""
  },
  "browser_action": {
    "default_title": "",
    "default_icon": "",
    "default_popup": "html/popup.html"
  },
  "author": "",
  "background": {
    "scripts": [
      "js/background.js"
    ],
    "persistent": false
  },
  "chrome_url_overrides": {
    "newtab": "html/index.html"
  },
  "incognito": "not_allowed",
  "permissions": [
    "activeTab",
    "alarms",
    "contextMenus",
    "notifications",
    "storage"
  ],
  "short_name": ""
}

I am checking the user permissions for notfications by doing this

 console.log("Request notifications");
    chrome.notifications.getPermissionLevel(function (result) {
      console.log(result); // this returns granted
    });

Solution

  • Thanks to @wOxxOm, I discovered the documentation for permissions and I was able to optionally allow users to enable notifications through this code snippet.

      getNotificationPermission() {
          chrome.permissions.request(
            {
              permissions: ["notifications"],
            },
            function (granted) {
              if (granted) {
                  // do this
              } else {
                 // do that
              }
            }
          );
        },
    

    In addition to this, I had to add the optional_permissions key in my manifest.json.

    manifest.json

      "optional_permissions":["notifications"],