4 min read

Permissions API 踩坑

Description

The Permissions API allows a web application to be aware of the status of a given permission, to know whether it is granted, denied or if the user will be asked whether the permission should be granted.

Permissions.query()

查询给定API的权限状态,返回状态,可以实时监听状态的变更。

我们可以利用它获取权限的状态,以及状态变更获得通知

State Type

  1. granted
  2. denied
  3. prompt

弹出的 权限询问框 有三种情况处理:

  1. 点击允许:会返回状态变更为 granted
  2. 点击禁止:会返回状态变更为 denied
  3. 点击 关闭按钮:只有 Notification API 特殊实现,会返回自身实现的一种状态,为:default

例子:

navigator.permissions.query({
name: 'microphone'
}).then(p => {
console.log('microphone', p.state);
// onchange 监听 状态变更
p.onchange = function () {
console.log('microphone', this.state);
};
});

关于 Requesting Permissions

也就是用户点击 允许、禁用、关闭 之后的回调

某些权限具有的API可以特殊实现 关闭 的回调

Notification

Notification API

例如 通知的 Notification.requestPermission

Notification.requestPermission(function(result) {
if (result === 'denied') {
console.log('Permission wasn\'t granted. Allow a retry.');
return;
} else if (result === 'default') {
console.log('The permission request was dismissed.');
return;
}
console.log('Permission was granted for notifications');
});

备注:3 次 点击关闭 权限询问框,Chrome 自动导致状态变更:prompt ——> denied,需要手动将权限置为其他状态

Navigator.getUserMedia

MediaDevices.getUserMedia() | MDN

关于 获取 麦克风、摄像头 权限,也有一套自己的实现

利用 navigator.getUserMedia 三种状态都能获取

// 旧API
navigator.getUserMedia({
audio: true,
video: true
}, function (stream) {
preview.src = window.URL.createObjectURL(stream);
preview.play();
recordVideo = RecordRTC(stream, {
type: 'video'
});
recordVideo.startRecording();
stop.disabled = false;
}, function (error) {
alert(error.toString());
});
// 新API
navigator.mediaDevices.getUserMedia({
audio: true
}).then((stream) => {
return stream;
}).catch(err => console.log(err.message))
// catch 的参数 是 DOMException 包装对象,在 web API中如何描述错误情况的对象

总结

1. 查看当前权限状态:

API:

navigator.permissions.query

首先, 一个权限的状态分为三种:

  1. granted (授予)
  2. denied (拒绝)
  3. prompt (询问)

后两种都是未获得用户授权的状态。

denied 状态包含 用户拒绝授权、无设备

2. 询问用户,获取授权权限:

API:

navigator.mediaDevices.getUserMedia

获取用户授权,会导致弹出询问框;如果没有设备,将不会弹出询问框

用户点击 授权询问框 的情况有三种

  1. 允许
  2. 禁止
  3. 关闭弹框

若没有设备,将直接返回 没有设备 的状态

用户在发生三种行为的回调,技术层面都可以获得

只有在 prompt 状态 ,询问框才会弹出

用户的 未授权 和 没有录音设备状态,在第二种是可以区分的

Reference