发布于 2026-01-06 7 阅读
0

权限 API 及其使用理由。

权限 API 及其使用理由。

嘿,大家好👋

在本文中,我将解释权限 API 的用途、重要性和使用案例,以及它对用户体验为何如此重要。

让我们开始吧🚀


目录


简介🟢

权限 API 可用于确定是否已授予(✅)或拒绝(❌)访问特定 API 的权限。

权限 API 为我们开发者提供了工具,使我们能够在权限管理方面实现更佳的用户体验。

这对于提高应用程序的可访问性和可用性至关重要。

权限 API 在 Safari 和 IE 中无法正常工作。


我们可以在哪里使用权限 API 🤔?

要了解更多关于剪贴板 API 的信息,请阅读我的文章(链接在此)

正在访问权限 API?

permissions该对象可在Navigator.permissions以下属性中找到👇

const permissions = navigator.permissions;
Enter fullscreen mode Exit fullscreen mode

为了检查特定 API 的权限状态,可以使用对象.query()上提供的` get_ ...permissions

.query()permissionDescriptor

.query()PermissionStatus


光说不练😅,咱们看看实际效果👇

-

1️⃣ 使用权限 API 检查剪贴板权限:

const permissions = navigator.permissions;

permissions.query({name: 'clipboard-write'}).then(cbWritePermission => {
console.log(cbWritePermission.state) // "granted"

// clipboard-write permission is granted by the browser automatically
});
Enter fullscreen mode Exit fullscreen mode

在上面的示例中,该state属性将告诉我们权限的状态。它可以有以下值::

granted权限已授予。

denied:权限已拒绝。

prompt:尚未请求权限。

让我们来看一个clipboard-read权限的例子👇

// suppose a scnerio where you want to do 
// something with the text before it get pasted by the user 
// in your application. 
// or you want to auto-capture copied text
// checking the item before doing anything
// with it is also good for security.

// reading text on a click
button.addEventListener("click", async () => {
  const cbReadPermissionStatus = await permissions.query({
    name: "clipboard-read",
  });
  if (
    cbReadPermissionStatus.state === "granted" ||
    cbReadPermissionStatus.state === "prompt"
  ) {
    const text = await navigator.clipboard.readText();
    // do something with the text
  } else {
    // show a nice error message, or ask for the permission nicely
  }
});

Enter fullscreen mode Exit fullscreen mode

2️⃣geolocation使用权限 API 检查权限:

  • 如果你正在开发一款应用,而用户的当前位置对于应用中某个功能的正常运行至关重要,那么这款应用正适合你。

请看下面的例子👇

button.addEventListener("click", async () => {
  const geoPermissionStatus = await permissions.query({ name: "geolocation" });

  if (
    geoPermissionStatus.state === "granted" ||
    geoPermissionStatus.state === "prompt"
  ) {
    navigator.geolocation.getCurrentPosition((pos) => {
      console.log(pos);
      // do something with the location
      // show friends around the user for eg
      // or move the map to the user's location
    });
  } else {
    // show warning that certain feature of the app
    // will not work if the location permission is not provided
  }
});
Enter fullscreen mode Exit fullscreen mode

其他 API 的权限可以使用与上述相同的步骤进行检查。

感谢您的阅读。❤️

请在推特上关注我。

祝您编程愉快!

文章来源:https://dev.to/sidmirza4/permissions-api-why-should-you-start-using-it-2k4d