Permissions API

143 阅读1分钟

译者:jiangtao

原文链接

很多函数功能,从Mobile迁移到PC使用时,需要用户的许可权限,比如geolocation, audio/video的使用权(如getUserMedia获取照相机的许可权限)等APIs. 我们大概认为这些API需要许可权限是一个好事,但是我看到了一个问题: 有时我们没有办法 在不向用户发一个请求 获取每一个API的权限级别。说这些为时过早。

我最近发现 Permissions API,它可以提供一个方法,不用为了使用权,向用户发一个请求询问权限级别的请求。来看一个简单的例子:

// Get the geolocation status (starts out as ""prompt"")
// ... meaning the user will be shown an access request if we want it
navigator.permissions.query({ name: 'geolocation' }).then(function(result) {
    /* result.status = ""prompt"" */
});

// Request geolocation access if we really want it
navigator.geolocation.getCurrentPosition(function(result) { /* ... */  })

// Assuming the user requested access, the permission is now ""granted""
navigator.permissions.query({ name: 'geolocation' }).then(function(result) {
    /* result.status = ""granted"" */
});

// Push notifications require options:
navigator.permissions.query({ name: 'push', userVisibleOnly:true }).then(function(result) { /* ... */ });

我喜欢这种新API,一种清晰的API,可以不需要向用户发任何请求信息就能获取权限级别。举个例子,如果权限级别是不允许的,不要询问用户权限做一些事情,或提示用户用另外一种形式来给予一个可用权限。

你看到这个API的优点了么? 来分享吧