Mer*_*erc 10 javascript firefox geolocation navigator
我正在尝试使用 Permissions API:https : //developer.mozilla.org/en-US/docs/Web/API/Permissions/query Firefox 应该支持它。(我目前使用的是Firefox Developer Edition 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
}
}
})
}
Run Code Online (Sandbox Code Playgroud)
例如,现在这在 Chrome 中一切正常。(顺便说一句:我使用 this.locationError 来显示一些信息窗口,说该应用程序只能在启用位置服务的情况下工作)
无论如何,如果我在 Firefox 中打开它,我会得到预期的提示:现在,如果我选中“记住这个决定”框并发送允许/阻止,我会看到它onchange按预期执行,让我有可能对用户决定。
但是,如果我不选中此框,而只是拒绝或允许一次,则不会调用 onchange,让我不知道实际发生了什么。此外,该状态仍然是“提示”。
我还尝试设置一段时间后再次检查权限的时间间隔,但它只会再次打开要求权限的提示。状态永远不会更新或从“提示”更改为“拒绝”或“授予”。
是不是我遗漏了什么,或者这是一个 Firefox 错误。
感谢您的任何提示
干杯
小智 2
我无法让 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();
}
}
})
Run Code Online (Sandbox Code Playgroud)
此解决方案将在 Chrome 浏览器中触发两次失败案例。为了避免这种情况,可以检查当前浏览器,以有条件地阻止onLocationFetchFalure向 Chrome 浏览器发送回调getCurrentPosition。
太长了;这里的修复是,我们不依赖于要触发的change事件/onchange函数,而是传递一个错误回调getCurrentPosition,当通过权限对话框更改位置权限时会触发该错误回调。1此错误回调提供用户拒绝/阻止位置权限时的错误代码。
| 归档时间: |
|
| 查看次数: |
3027 次 |
| 最近记录: |