为什么 Chrome iOS 在授予地理位置时发送提示

问题描述 投票:0回答:1

我想在我的网站的某些部分允许地理定位,为此,我更愿意在客户端页面上请求许可,然后再提示他们浏览器地理定位权限请求。

所以我用类似下面的东西收集

response.state
...

navigator.permissions.query({ name: "geolocation" }).then((response) => {
  // do stuff with response.state
});

然后,如果状态是

prompt
,我将渲染另一个页面,很好地要求他们允许通过单击按钮进行地理定位。这个按钮会触发这个代码

navigator.geolocation.getCurrentPosition(
  (position) => {
    if (position) {
      // location was granted for sure, we do stuff
    }
  },
  () => {
    // this means the client didn't accept geolocation
  }
);

它在我的计算机上的所有浏览器中都能完美运行。但是,在允许地理定位后在 Chrome iOS 上刷新页面时,当状态应为

prompt
时,它仍然处于
granted
状态;尽管状态是
prompt
,但我实际上可以获得确切的位置,这对我来说没有什么意义。

Chrome iOS 发生了什么?有解决方法吗? 行为不同,但我无法查明原因,也找不到有关它的文档。这种改进的用户体验至关重要。我可以提示它并要求最好的,但我希望客户首先批准。

javascript ios iphone google-chrome geolocation
1个回答
0
投票

最终,Chrome iOS 的行为不稳定,所以我必须自己找出解决方法。

我只是想在

prompt
状态下显示某种 UI,所以我必须添加这些助手

export function setGeoGranted() {
  localStorage.setItem("permission-granted", "true");
}

export function isGeoGranted() {
  return !!localStorage.getItem("permission-granted");
}

当渲染 UI 进行提示时,我只需仔细检查如下

!isGeoGranted() && stateGeolocation === "prompt"

最后当用户界面授予权限时,我也添加了其中的逻辑

navigator.geolocation.getCurrentPosition(
  (position) => {
    if (position) {
      setGeoGranted();
      window.location.reload();
    }
  },
  () => {
    // this means the client didn't accept geolocation
  }
);

就我而言,它有效。它将对

prompt
状态产生疑问并要求确定,一旦存储了项目,我们就认为这是确定的,因此我们不会再次询问,只是有逻辑将位置进一步降低。

但是,我没有找到任何关于 Chrome 为何会出现这种行为的解释,因此,如果有人阅读本文并了解更多详细信息,请随时将其注释掉。

© www.soinside.com 2019 - 2024. All rights reserved.