Search code examples
javascriptfirefoxpermissionscross-browsernavigator

How to tell if navigator.permissions.query with a certain permission is supported


I have the following code:

if (navigator.permissions && navigator.permissions.query) {
  navigator.permissions.query({
    name: 'clipboard-write'
  }).then(function(result) {
    if (result.state === 'granted') {
      //Do something!
    } else{
      //Not granted...
    }
} else {
  //Does not support navigator.permissions
}

This works in Safari and Chrome. In Firefox however, it throws this error:

TypeError: 'name' member of PermissionDescriptor 'clipboard-write' is not a valid value for enumeration PermissionName.

The navigator.permissions.query is supported, just not clipboard-write. So, how do I see if the browser supports:

navigator.permissions.query({name:'clipboard-write'})

I have thought I could maybe just check what browser is being used, but I think there has to be a better way of doing it.

EDIT ( try / catch )

I tried try/catch with the following code:

try {
  navigator.permissions.query({
    name:'clipboard-write'
  });
}
catch(error) {
  console.log(error);
}

Unfortunately this does not catch in Firefox.


Solution

  • A bit late to the party, but seeing that you didn't get any answer, and in case anyone stumbles upon this question:

    navigator.permissions returns a Promise, so in addition to .then() you can use .catch() for when the Promise is rejected.

    clipboard-write seems to be availabie in Firefox now, so I used camera in this example, which will still fail in Firefox (any nonsensical value would do as well in order to test this).

    navigator.permissions.query({
        name: 'camera'
      })
      .then((permissionObj) => {
        console.log(permissionObj);
        // ... check the permission object ...
      })
      .catch((error) => {
        // couldn't query the permission
        console.error(error);
      });