The Permission API is not a new standard; it has been a standard since 2015. The main purpose of this API is to provide a unified interface for querying API permissions. 😌
If we were using the Notification API, we would need to do this:
Notification.requestPermission().then(function (permission) {
if (permission === 'granted') {
let notification = new Notification('helloooooo')}else if(/ *... * /) {
// ...
} else {
// ...}})Copy the code
The requestPermission method is called first, and then the callback function checks whether the permission argument is GRANTED. If so, the permission has been obtained and an instance of the Notification can be created
Then look at how the Geolocation API obtains permissions:
navigator.geolocation.getCurrentPosition(console.log, console.error)
Copy the code
Oh roar? You don’t need to explicitly call and verify that permissions have been obtained, but rather check through the callback function 😵
As a result, this can sometimes lead to confusion, and the Permission API is designed to solve this problem
So how to use ❓
Permissions the permissions function has a query method that queries the status of the permissions:
navigator.permissions.query({ name: 'geolocation' }).then(status= > {
console.log('Current status${status.state}`)
// status is an instance of PermissionStatus
})
Copy the code
Receives an object whose attribute name is the name of the API to be queried, with the following effect:
He has three states:
- granted
- denied
- prompt
The PermissionStatus also has a change event that can be listened for further processing of permission changes
Similarly, we pass the parameter to query for Notification:
navigator.permissions.query({ name: 'notifications' }).then(status= > {
console.log('Current status${status.state}`)
status.onchange = function() {
console.log('State changeThe ${this.state}`.this.state)
}
})
Copy the code
The effect is as follows:
Of course, if you need to obtain permissions, you still need to write code according to a specific API. Permission only provides query functionality 😫
Supplement:
Query to the browser also supports the navigator. Permissions. The request and the navigator. Permissions. RequestAll method, is used to request permission, try the following:
navigator.permissions.request({ name: 'geolocation' }).then(console.log)
Copy the code
The browser will pop up and ask if you are authorized:
In this way Permission can also provide the ability to request Permission