【问题标题】:Is there a way to check if geolocation has been DECLINED with Javascript?有没有办法检查地理位置是否已被 Javascript 拒绝?
【发布时间】:2011-08-30 20:20:48
【问题描述】:

如果地理定位被拒绝,我需要 JavaScript 来显示手动输入。

我尝试过的:

Modernizr.geolocation
navigator.geolocation

两者都没有描述用户之前是否拒绝访问地理位置。

【问题讨论】:

  • 接受的答案更改为@endless

标签: javascript html w3c-geolocation


【解决方案1】:

watchPositiongetCurrentPosition 都接受第二个回调,当出现错误时调用该回调。错误回调为错误对象提供参数。对于拒绝的权限,error.code 将是 error.PERMISSION_DENIED(数值 1)。

在此处阅读更多信息:https://developer.mozilla.org/en/Using_geolocation

例子:

navigator.geolocation.watchPosition(function(position) {
    console.log("i'm tracking you!");
  },
  function(error) {
    if (error.code == error.PERMISSION_DENIED)
      console.log("you denied me :-(");
  });

编辑:正如@Ian Devlin 指出的那样,Firefox(在本文发布时为 4.0.1)似乎不支持这种行为。它在 Chrome 和 可能 Safari 等中按预期工作。

【讨论】:

  • 权限被拒绝错误与此人拒绝允许浏览器收集他们的信息这一事实无关。
  • @Ian Devlin:你确定吗? W3C 草案说当“位置获取过程失败,因为文档没有使用 Geolocation API 的权限”时会给出 PERMISSION_DENIED 错误。但是,我无法让这种行为在 Firefox 中起作用——尽管它在 Chrome 中的工作方式与(我)预期的一样。
  • 不,我现在不确定! :-) 我确实在某处读到 Firefox 没有正确实现这一特定位。
  • 截至 2013 年 8 月,Firefox(23.0) 仍然不支持此功能。我花了很长时间才弄清楚这一点。
  • 2018 年您好!当用户现在拒绝权限时,Firefox 61 会抛出正确的错误代码,而不管方法如何(从不与现在不)。
【解决方案2】:

根据 W3C geolocation specification,您的 getCurrentPosition 调用可以返回成功回调和失败回调。但是,将针对发生的 any 错误调用您的失败回调,该错误是以下之一: (0) 未知; (1) 许可被拒绝; (2) 职位不可用;或 (3) 超时。 [Source: Mozilla]

在您的情况下,如果用户明确拒绝访问,您想要做一些特定的事情。您可以检查失败回调中的error.code 值,如下所示:

navigator.geolocation.getCurrentPosition(successCallback,
    errorCallback,
    {
        maximumAge: Infinity,
        timeout:0
    }
);

function errorCallback(error) {
    if (error.code == error.PERMISSION_DENIED) {
        // pop up dialog asking for location
    }
}

【讨论】:

  • 2018 年您好!当用户现在拒绝权限时,Firefox 61 会抛出正确的错误代码。
【解决方案3】:

修复 Firefox 问题非常简单。在我的例子中,我将地理位置保存在 Javascript 上的一个名为 geolocation 的全局变量中。在使用这个变量之前,我只是检查是否未定义,如果是,我只是从 IP 获取地理位置。

在我的网站中,我第一次获取位置没有任何问题,但我在我的简短示例中看到,因为太快了,所以第一次没有时间获取地理位置。

无论如何这只是一个例子,你应该在每种情况下进行调整。

var geolocation = {};
getLocation();

$(document).ready(function(){
    printLocation(); // First time, hasn't time to get the location
});

function printLocation(){
    if(typeof geolocation.lat === "undefined" || typeof geolocation.long === "undefined"){
        console.log("We cannot get the geolocation (too fast? user/browser blocked it?)");
        // Get location by IP or simply do nothing
    }
    else{
        console.log("LATITUDE => "+geolocation.lat);
        console.log("LONGITUDE => "+geolocation.long);
    }
}

function getLocation() {
    // If the user allow us to get the location from the browser
    if(window.location.protocol == "https:" && navigator.geolocation)
        navigator.geolocation.getCurrentPosition(function(position){
            geolocation["lat"] = position.coords.latitude;
            geolocation["long"] = position.coords.longitude;
            printLocation(); // Second time, will be return the location correctly
        });
    else{
        // We cannot access to the geolocation
    }
}

PS:我没有足够的声誉来评论上述答案,所以我不得不创建一个新答案。对此感到抱歉。

【讨论】:

  • 2018 年您好!当用户现在拒绝权限时,Firefox 61 会抛出正确的错误代码。
【解决方案4】:

在不提示用户的情况下,您可以使用新的权限 api,这是可用的:

navigator.permissions.query({ name: 'geolocation' })
.then(console.log)

(仅适用于 Blink 和 Firefox)

http://caniuse.com/#feat=permissions-api

【讨论】:

  • @trev9065 Blink 是 Chrome 使用的浏览器引擎。
  • 又一次 safari 是新的 ie :(
【解决方案5】:

内联权限检查

可能的值为promptgranteddenied

const permissionStatus = await navigator?.permissions?.query({name: 'geolocation'})
const hasPermission = permissionStatus?.state // Dynamic value

注意:这需要在 async 函数中

默认值:

如果要处理失败的情况,请在第二行添加可选的?? myDefaultValue

链接:

【讨论】:

  • 有点重复我自己的答案来自所有?
  • 适合展示Inline Null Check的使用提示:@babel/plugin-proposal-optional-chaining
【解决方案6】:

navigator.geolocation.watchPosition(function(position) {
    console.log("i'm tracking you!");
  },
  function(error) {
    if (error.code == error.PERMISSION_DENIED)
      console.log("you denied me :-(");
  });

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2020-01-07
  • 1970-01-01
  • 2011-03-24
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 2011-10-01
  • 2020-11-05
  • 1970-01-01
相关资源
最近更新 更多