← 中文资源

简体中文版本

permissions.query 守卫功能开关

调用受限 API 前先用 navigator.permissions.query 查询授权状态,按 granted/denied/prompt 分支处理,并监听 change 响应运行时变化。

阅读英文原文

实现说明

await 点把异步工作排成序列,拒绝落在取结果的那一行。 各个操作都建立在顶层绑定之上:status。

使用要点

  • 浏览器才是这里的运行环境:navigator 在 Node 里拿不到。
  • 跑完文件,输出里会留下标记——geolocation:、safe to watch position immediately、show settings help instead of a broken button。

常见问题

依赖情况复杂吗?

一点也不复杂:零依赖,没有要锁版本或审计的东西。 文件的状态由几个模块级绑定持有:status。

核心语句

status.addEventListener('change', () => {
  console.log('geolocation changed:', status.state);
});
const status = await navigator.permissions.query({ name: 'geolocation' });

代码示例

// permissions.query reports the current grant state without prompting
const status = await navigator.permissions.query({ name: 'geolocation' });
console.log('geolocation:', status.state);

// gate the feature path on the answer instead of calling and failing
if (status.state === 'granted') {
  console.log('safe to watch position immediately');
} else if (status.state === 'denied') {
  console.log('show settings help instead of a broken button');
}

// the state can change at runtime: 'change' fires on grant or revoke
status.addEventListener('change', () => {
  console.log('geolocation changed:', status.state);
});