我正在使用地理定位来检测位置...
if ("permissions" in navigator) {
navigator.permissions.query({ name:'geolocation' }).then((result) => {
if (result.state === 'granted') {
console.log("granted")
} else if(result.state === 'denied'){
console.log("denial")
} else {
console.log("prompt")
}
});
}
在 Android 网络浏览器中一切正常,但在 iOS 网络浏览器中,即使我已经允许定位,输出也始终是“提示”,即使我刷新了很多次。
我做错了什么?是否涉及一些谷歌控制台扩展? iPhone需要使用google付费服务(google console)吗?该问题仅出现在 iPhone/iOS 中(甚至在 Safari 16+ 上),其他设备都没有问题。 iOS 16+ 应支持该功能。
最佳答案
Safari 对隐私非常严格,如果您在以下位置查看 iO 中的位置共享设置:设置
- 隐私和安全
- 位置服务
- Safari 网站
即使您在使用应用程序时启用它们,您也会看到解释文本指出:
App explanation: "Websites you visit may request your location"
这意味着,即使授予了此访问权限,网站仍必须提示用户请求权限,无论您是否已在设置中授予该权限。换句话说,您授予 Safari 访问您所在位置的权限,而不是您在 Safari 中访问的网站。
在您的情况下,您可以通过使用 getCurrentPosition
方法请求用户位置来触发提示:
function success(pos) {
var coordinates = pos.coords;
console.log(
`Your location is: ${coordinates.latitude}} ${coordinates.longitude}`
);
}
function error(error) {
console.warn(`Error: ${error.message}`);
}
if ("permissions" in navigator) {
navigator.permissions.query({
name: "geolocation"
}).then((result) => {
if (result.state === "granted") {
console.log("granted");
} else if (result.state === "denied") {
console.log("denial");
} else {
navigator.geolocation.getCurrentPosition(success, error, {
timeout: 4000,
maximumAge: 0
});
}
});
}
注意这在代码段 iframe 中不起作用,因此这里是 codesandbox example你可以在iOs中用Safari打开来测试。如果您启用了 Safari 的位置服务,您应该会看到以下提示:
关于javascript - iOS Safari 16 已允许地理定位,但导航器权限仍然显示 "prompt",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75872915/