我正在尝试使用权限 API:https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
Firefox应该支持哪个。
(我目前使用的是 Firefox 开发者版 66.0b14)。
我有一个页面,我最初在其中检查用户权限。
就像是;
if (navigator.permissions) {
navigator.permissions.query({ name: 'geolocation' }).then(result => {
if (result.state === 'granted') {
this.getCurrentPosition()
} else if (result.state === 'prompt') {
this.getCurrentPosition()
console.log('Permissions requested. Waiting for user input...')
} else if (result.state === 'denied') {
this.locationError = true
}
result.onchange = event => {
if (event.target.state === 'granted') {
this.locationError = false
this.getCurrentPosition()
console.log('Thanks for letting us know...')
} else if (event.target.state === 'denied') {
this.locationError = true
}
}
})
}
例如,现在这在 Chrome 中一切正常。
(顺便说一句:我使用 this.locationError 来显示一些信息窗口,说明该应用程序只能在启用位置服务的情况下工作)
无论如何,如果我在 Firefox 中打开它,我会得到预期的提示:
现在,如果我选中“记住这个决定”框并发送允许/阻止,我会看到
onchange
按预期执行,使我有可能对用户的决定使用react。但是,如果我不选中此框,而只是拒绝或允许一次,则不会调用 onchange,让我不知道实际发生了什么。同样,这个状态仍然是“及时的”。
我还尝试设置一个时间间隔以在一段时间后再次检查权限,但它只会打开提示请求权限。状态永远不会从“提示”更新或更改为“拒绝”或“授予”。
有什么我遗漏的东西,或者这是一个 Firefox 错误。
感谢您的任何提示
干杯
最佳答案
我无法让 onchange 函数或更改事件为 Firefox 工作,但能够找到一种解决方法,该解决方法同样可以识别权限更改:
注意:此修复仅在您使用 geolocation.getCurrentPosition
时有效。
navigator.permissions.query({
name: 'geolocation'
}).then(function(result) {
const onLocationFetchSuccess = (position) => {
/*
Consume location coordinates here and proceed as required
using position.coords.latitude and position.coords.longitude
*/
};
const onLocationFetchFailure = (error = {}) => {
// Error code 1 corresponds to user denying/blocking the location permission
if (error.code === 1) {
// Respond to failure case as required
}
};
navigator.geolocation.getCurrentPosition(onLocationFetchSuccess, onLocationFetchFailure);
if (result.state === 'denied') {
onLocationFetchFailure();
}
// This will still work for Chrome
result.onchange = function() {
if (result.state === 'denied') {
onLocationFetchFailure();
}
}
})
此解决方案将触发两次 Chrome 浏览器的故障案例。为了避免这种情况,可以检查当前浏览器以有条件地阻止发送 onLocationFetchFalure
回调到 getCurrentPosition
适用于 Chrome 浏览器。TLDR;这里的解决方法是,而不是依赖
change
事件/onchange
要触发的函数,我们将错误回调传递给 getCurrentPosition
通过权限对话框更改位置权限时触发。此错误回调提供的错误代码为 1
当用户拒绝/阻止位置权限时。
关于javascript - Navigator.permissions.query : Geolocation onChange not working in Firefox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55127053/