permissions_JavaScript Permissions API导览

permissions

If you have ever created a web application which requires different features (like push notifications, webcam access, midi access), you probably noticed that their APIs look very different.

如果您曾经创建过一个需要不同功能(例如推送通知,网络摄像头访问,MIDI访问)的Web应用程序,则您可能会注意到它们的API看起来非常不同。

// for the geolocation API you need to call getCurrentPosition to check if geolocation is accessible
navigator.geolocation.getCurrentPosition(gotLocation, didNotGetLocation);

// for notifications we can directly check on the Notification object

if (Notification.permission == 'granted')
  // do notification stuff
if (Notification.permission == 'denied')
  // ask for notification access ....

This is not very handy.

这不是很方便。

The Permissions API allows us to have overview of the permissions available on our pages. What we mean by “permission” is whether we can access a specific feature with our code. Features that require permission to access them with code are called powerful features. Camera, midi, notifications, geolocation are all powerful features.

Permissions API使我们可以概览页面上可用的权限。 “权限”是指我们是否可以使用代码访问特定功能。 需要权限才能使用代码访问它们的功能称为强大功能。 相机,MIDI,通知,地理位置都是强大的功能。

All powerful feature’s APIs are a bit different. Thus, it can be a pain to figure out what is the state of each feature’s permissions. With the Permissions API, we manage all the permission’s statuses with a single interface.

所有功能强大的API都有所不同。 因此,弄清楚每个功能的权限状态是一件很痛苦的事情。 借助Permissions API,我们可以通过一个界面管理所有权限的状态。

权限API基础 (Permissions API Basics)

The permission API is very experimental at this stage and should be used carefully. You should only use it if it is mission critical and you can keep up with future breaking changes. For instance, a few browsers used to support navigator.permissions.revoke but it is now deprecated.

权限API在此阶段尚处于试验阶段,应谨慎使用。 仅当它对任务至关重要并且可以跟上未来的重大变化时,才应使用它。 例如,一些浏览器曾经支持navigator.permissions.revoke但现在已弃用。

At the time of the writing, query is the only property we can access from then permissions interface. query takes an object as an argument called a PermissionDescriptor. The permission descriptor has one field called name, which is the name of the permission you want to access.

在撰写本文时, query是我们可以从permissions界面访问的唯一属性。 query将一个对象作为称为PermissionDescriptor的参数。 权限描述符具有一个名为name字段,这是您要访问的权限的名称。

// This query will give us information about the permissions attached to the camera
navigator.permissions.query({name: 'camera'})

The query returns a promise which resolves to a PermissionStatus. PermissionStatus has two fields: state and onchange.

该查询返回一个承诺,该承诺解析为PermissionStatus 。 PermissionStatus有两个字段: stateonchange

navigator.permissions.query({name: 'camera'}).then( permissionStatus => {
  console.log(permissionStatus)
  // in my browser on this page it logs:
  //{
  //   status: "prompt",
  //   onchange: null,
  // }
})

state has 3 possible states: “granted”, “denied” and “prompt”. “granted” means that we have access to the feature. “denied” means that we won’t be able to access the feature. “prompt” means that the User-Agent (i.e. the browser) will ask the user for permission if we try to access that feature.

state有3种可能的状态:“允许”,“拒绝”和“提示”。 “授予”表示我们有权使用该功能。 “已拒绝”表示我们将无法使用该功能。 “提示”表示如果我们尝试访问该功能,则User-Agent(即浏览器)将询问用户许可。

Some PermissionDescriptor have additional fields and you can read more about them here. For example, camera’s PermissionDescriptor has an additional field called deviceId if you want to target a specific camera. Your query might look like this: .query({name: 'camera', deviceId: "my-device-id"}).

一些PermissionDescriptor具有其他字段, 您可以在此处阅读有关它们的更多信息 。 例如, camera的PermissionDescriptor如果要定位到特定的camera,则有一个名为deviceId的附加字段。 您的查询可能看起来像这样: .query({name: 'camera', deviceId: "my-device-id"})

onchange is an event listener which activates whenever the permissions of the queried feature changes.

onchange是一个事件侦听器,只要所查询功能的权限发生更改,它就会激活。

navigator.permissions.query({name:'camera'}).then(res => {
  res.onchange = ((e)=>{
    // detecting if the event is a change
    if (e.type === 'change'){
      // checking what the new permissionStatus state is
      const newState = e.target.state
      if (newState === 'denied') {
        console.log('why did you decide to block us?')
      } else if (newState === 'granted') {
        console.log('We will be together forever!')
      } else {
        console.log('Thanks for reverting things back to normal')
      }
    }
  })
})

所有权限API (All Permissions API)

There are a lot of different powerful permissions and browser support is very uneven. In the following script, you can see all the permissions described by W3C’s editor’s draft in the permissionsName variable. The getAllPermissions function returns an array with the different permissions available and their state. Please note that the result will change depending on your browser, the user’s preference and of course the website’s setup.

有许多不同的强大权限,并且浏览器支持非常不平衡。 在以下脚本中,您可以在permissionsName变量中查看W3C编辑器的草稿所描述的所有permissionsNamegetAllPermissions函数返回一个具有不同可用权限及其状态的数组。 请注意,结果将根据您的浏览器,用户的喜好以及网站的设置而有所不同。

const permissionsNames = [
  "geolocation",
  "notifications",
  "push",
  "midi",
  "camera",
  "microphone",
  "speaker",
  "device-info",
  "background-fetch",
  "background-sync",
  "bluetooth",
  "persistent-storage",
  "ambient-light-sensor",
  "accelerometer",
  "gyroscope",
  "magnetometer",
  "clipboard",
  "display-capture",
  "nfc"
]

const getAllPermissions = async () => {
  const allPermissions = []
  // We use Promise.all to wait until all the permission queries are resolved
  await Promise.all(
    permissionsNames.map(async permissionName => {
        try {
          let permission
          switch (permissionName) {
            case 'push':
              // Not necessary but right now Chrome only supports push messages with  notifications
              permission = await navigator.permissions.query({name: permissionName, userVisibleOnly: true})
              break
            default:
              permission = await navigator.permissions.query({name: permissionName})
          }
          console.log(permission)
          allPermissions.push({permissionName, state: permission.state})
        }
        catch(e){
          allPermissions.push({permissionName, state: 'error', errorMessage: e.toString()})
        }
    })
  )
  return allPermissions
}

If I then run the following code in my developer console on Alligator.io:

如果然后我在Alligator.io的开发人员控制台中运行以下代码:

(async function () {
  const allPermissions = await getAllPermissions()
  console.log(allPermissions)
})()

Here’s a screenshot of what I get at the console:

这是我在控制台上得到的屏幕截图:

工人的权限 (Permissions in Workers)

So far we only used the navigator.permissions API because it is much easier to write concise examples. The Permissions API is also available inside of workers. WorkerNavigator.permissions allows us to check permissions inside our workers.

到目前为止,我们只使用了navigator.permissions API,因为编写简洁的示例要容易得多。 工人内部也可以使用Permissions API。 WorkerNavigator.permissions允许我们检查工作人员内部的权限。

Hopefully you now have a better idea on how to use the Permissions API. It’s not very complicated, nor is it essential but it does make it much easier for us to manage permissions in our JavaScript-based apps. There will probably be some new features and changes to the API and we’ll keep you updated!

希望您现在对如何使用Permissions API有更好的了解。 它不是很复杂,也不是必不可少的,但是它确实使我们更轻松地管理基于JavaScript的应用程序中的权限。 API可能会有一些新功能和更改,我们将随时为您更新!

翻译自: https://www.digitalocean.com/community/tutorials/js-permissions-api

permissions

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值