Permissions API for the Web

If you’ve worked with the Geolocation
API
before, chances are you’ve wanted to check if you had permission to use
Geolocation without causing a prompt. This simply wasn’t possible. You had to request the current position and this would indicate the permission state or cause a prompt to be shown to the user.

Not all APIs work this way. The Notifications API has its own way of allowing
you to check the current permission state viaNotification.permission.

As the web platform grows in API’s, there needs to be a single, standard way for
developers to check the status of a permission rather than having to remember
how each and every API works. The Permission
API, available in Chrome version 43, is
intended to be this single, standard way to check the permission status of an API.

The query method takes aPermissionDescriptor
object, where you define the permission’s name. The response is a Promise
resolving to aPermissionStatus
object. From this object, you can check the status with permissionStatus.status
for ‘granted’, ‘denied’ or ‘prompt’. You can also also implement an event
handler for permissionStatus.onchange and handle changes to the permission
status of an API.

Supported PermissionDescriptors

In the above example, we highlight how to query the permission state for
geolocation with the following permission descriptor: {name:'geolocation'}.

The Notification permission descriptor is similar in that it only requires a
name attribute: {name:'notifications'}.

Push andmidi each have an additional
parameter that is specific to that API.

For the push permission, you can supply a userVisible parameter. This indicates
whether you wish to show a notification for every push message or be able to
send silent push notifications (At the moment Chrome only supports push messages
with notifications). You’d use it like so:

navigator.permissions.query({name:'push',userVisible:true})

Midi allows a sysex parameter. This indicates whether you need to and/or receive
system exclusive messages. For midi this would be:

navigator.permissions.query({name:'midi',sysex:true})

Requesting Permissions

Requesting permission from the user depends on the specific API. For example,
geolocation would show a permission prompt when you call getCurrentPosition().

The point here is that the Permission API allows a consistent way to monitor the
status of permissions while being able to support the range of APIs currently on
the web.

The big advantage of this is that it allows you to build better experiences for
your users, only prompting when it’s obvious to the user why you need extra
privileges and taking full advantage of these APIs when you know you have been
granted permission.