检查浏览器的位置是否仅打开一次

时间:2016-11-17 09:11:04

标签: javascript html geolocation

我正在使用navigator.geolocation.watchPosition函数检查浏览器的位置是否打开。但是这个函数被多次调用(没有页面加载)。例如,如果我切换到另一个选项卡并返回页面的选项卡,则会调用它。

我的代码是

<script>

navigator.geolocation.watchPosition(function (position) {
   alert("i'm tracking you!");
},

function (error) {
   if (error.code == error.PERMISSION_DENIED){
      alert("you denied me :-(");
   }
});

</script>

我怎样才能只调用一次该功能?

5 个答案:

答案 0 :(得分:1)

只需跟踪watchPosition功能是否触发了您的功能:

var firedAlready = false;

navigator.geolocation.watchPosition(function (position) {
   if(!firedAlready) {
      alert("i'm tracking you!");
      firedAlready = true;
   }
},

function (error) {
   if (error.code == error.PERMISSION_DENIED){
      alert("you denied me :-(");
   }
});

答案 1 :(得分:0)

尝试为您的代码创建一个机箱!这将确保它只执行一次。

var something = (function() {
    var executed = false;
    return function () {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

答案 2 :(得分:0)

还考虑使用navigator.geolocation.clearWatch()禁用事件处理程序。 E.g:

var id;
id = navigator.geolocation.watchPosition(function (position) {
    alert("i'm tracking you!");
    navigator.geolocation.clearWatch(id);
},
function (error) {
    if (error.code == error.PERMISSION_DENIED){
        alert("you denied me :-(");
        // I suspect this is actually unnecessary since we were denied.
        navigator.geolocation.clearWatch(id);
    }
});

有关详细信息,请查看the MDN page about Geolocation.clearWatch()

答案 3 :(得分:0)

您可以在获得结果后清除位置监听器。

enter link description here

或者您可以使用navigator.geolocation.getCurrentPostion来测试是打开还是关闭。

答案 4 :(得分:0)

您需要保存在本地存储中检查权限的状态,以便长时间使用,或者更好地使用该网站的Cookie并在此处保存首选项。

如果您只在重新加载页面时执行变量,则重新初始化变量。

您的数据需要持久。

如果您是饼干新手,请从这里开始 http://www.w3schools.com/js/js_cookies.asp

相关问题