有一小段调用 navigator.geolocation
的 javascript 代码。
我有一个 if
语句,如果用户允许调用,它会显示纬度和经度。但是,else
部分没有运行。
如果我运行下面的代码,浏览器会提示我允许;如果我允许,则显示坐标。但是,如果我点击 block ,即使有 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
来检查权限。
导航器方法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.');
}
关于Javascript 浏览器导航器权限其他部分未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52730820/