不同 API 詢問 permission 的方式並不相同。此 API 旨在提供一致性的 permission 體驗。
用法
透過 navigator.permissions
來訪問不同的 API permission ,並透過 promise
串連處理方式。
navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
// ...
}
});
result.state
有以下幾個值:
- granted
- prompt
- denied
Notification Permission 用法
以下是不使用 Permission API 來詢問 notification API 權限的方式,就是用 Notification API 。
1. 先檢查瀏覽器是否支援通知!("Notification" in window)2. 查看使用者是否已經允許通知Notification.permission === "granted"3. 若允許,就可以製作一筆通知4. 如果沒有允許,要詢問是否要允許通知if (Notification.permission !== 'denied'
|| Notification.permission === "default") {
Notification.requestPermission(function (permission) {
// If the user accepts, let's create a notification
if (permission === "granted") {
let notification = new Notification("Hi there!");
}
});
}
補充說明
原本範例有 revoke
可以用來重新設定權限,但我發現其實已經不能用了,如果你拒絕透露位置的權限,你想透過 Permission API 去恢復,會遇到以下 log:
Permission currently denied; future features of the Permissions API will allow us to request permission here.Currently you have to reset the permission state using the browser UI.In Firefox it is done with Tools > Page Info > Permissions > Access Your Location.
主要是說,目前 permission 為 denied,Permissions API 未來會讓我們在此處詢問 permission,現在只能從瀏覽器的介面去重新設定。
所以如果你檢查使用者權限後發現他是拒絕的,你可能只能透過 promise
提供教學讓使用者去開放權限。
參考
- https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API
有各種 API 支援的狀況,還有更進一步參考的文章