【问题标题】:Javascript browser navigator permissions else section not triggeringJavascript浏览器导航器权限其他部分未触发
【发布时间】:2019-03-14 19:26:30
【问题描述】:

有一小段 JavaScript 代码调用navigator.geolocation

我有一个if 语句,如果用户允许呼叫,它可以显示纬度和经度。但是,else 部分没有运行。

如果我运行下面的代码,浏览器会提示我允许;如果我允许,则显示坐标。但是,如果我点击阻止,即使有 else 部分,也不会发生任何事情。

<body>
  <br> <p id="ChangeSring">Test</p>
  <script>
  var x = document.getElementById("ChangeSring");
  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(SavePosition);
  } else { 
      x.innerHTML = "Geolocation is not supported by this browser.";
      document.cookie = 'location=false;path=/form_handler';
  }

  function SavePosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;
    document.cookie = 'location=true;path=/form_handler';
    document.cookie = 'latitude='+ position.coords.latitude +';path=/form_handler';
    document.cookie = 'longitude='+ position.coords.longitude +';path=/form_handler';
  }
  </script>

  <form action="/form_handler" _lpchecked="1">
    Enter value:
    <input type="text" name="SomeVar"><br>
    <input type="submit" value="search">
  </form>
</body>

【问题讨论】:

  • 您查看过控制台日志吗?有什么有用的吗?
  • 我认为 else 语句只有在浏览器不支持时才会被调用,如果被阻止则不会。

标签: javascript html web browser navigator


【解决方案1】:

您不能使用else 来检查权限。

导航器方法getCurrentPosition 接受成功和错误回调。 如果权限被拒绝,将调用错误回调。

if (navigator.geolocation) { // this checks if navigator is supported at all
  navigator.geolocation.getCurrentPosition(console.log, () => {
    console.log('Permission denied')
  });
} else {
  console.log('Geolocation is not supported by this browser.');
}

【讨论】:

    【解决方案2】:

    getCurrentPosition 采用successerror 函数。 参考:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition#Example

    function errorGettingPosition(positionError) {
      x.innerHTML = "Geolocation is not supported by this browser.";
      document.cookie = 'location=false;path=/form_handler';
    }
    
    navigator.geolocation.getCurrentPosition(SavePosition, errorGettingPosition)
    

    【讨论】:

      【解决方案3】:

      if-else 语句正在检查 navigator.geolocation 是否未定义(即使您不希望浏览器知道您的位置也不是)按照其他答案正确处理权限

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-18
        • 2018-08-08
        • 1970-01-01
        相关资源
        最近更新 更多