我对地理定位 API 有一个具体问题。这是我的场景:
- 用户登录到禁用 GPS 位置的页面(在 Chrome - Android 中)。
- 页面上有一个按钮,按钮的onClick会触发
Geolocation.getCurrentPosition
- 地理位置进入错误回调,并显示错误消息“用户拒绝地理位置”
- 用户转到 Android 设置(主要在通知抽屉中)并打开位置信息
- 用户再次点击按钮(此时位置可用)即可获取坐标
- 但是,Geolocation api 仍然会抛出错误“User Denied Geolocation”
—
- 目前,只有当用户刷新页面并按下按钮时,地理定位请求才会起作用(注意:位置仍处于启用状态)
有没有办法在不刷新浏览器的情况下完成这项工作?
这是 jsbin 链接:https://output.jsbin.com/pihenud
最佳答案
最后,我能够使用 iFrame hack 解决这个问题。
解决方案如下:
不要在主窗口中请求权限,而是动态创建一个 iFrame 并调用其中的geolocation.getCurrentPosition
。现在,我们可以使用 window.postMessage
将位置数据传递到父浏览器窗口。
当我们必须再次重试地理定位请求时,我们只需重新加载 iframe - 这将具有新的站点设置。
如果有人想尝试,这里是 iframe 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Namshi Geolocation</title>
</head>
<body>
<script type="text/javascript">
var sendMessage = function(result){
window.postMessage(JSON.stringify(result), window.location.origin);
};
var triggerGeolocationRequest = function(){
var options = {
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
};
var result;
if(window.navigator.geolocation){
window.navigator.geolocation.getCurrentPosition(function(position){
var result = {
type: 'success',
data: {lat: position.coords.latitude, lng: position.coords.longitude}
};
sendMessage(result);
}, function(err){
var result = {
type: 'error',
data: { message: err.message, code: err.code }
};
sendMessage(result);
}, options)
} else {
result = {
type: 'error',
data: { message: 'No Geolocation API' }
};
sendMessage(result);
}
};
window.addEventListener('load', triggerGeolocationRequest);
</script>
</body>
</html>
在您的应用程序代码中,您可以使用一个实用程序来注入(inject) iFrame。请参阅下面的代码:
utils.getCurrentPosition = function(){
return new Promise(function(resolve, reject){
var ifr = document.createElement('iframe');
ifr.style.opacity = '0';
ifr.style.pointerEvents = 'none';
ifr.src = location.origin + '/geo.html'; // the previous html code.
document.body.appendChild(ifr);
ifr.contentWindow.addEventListener('message', function(message){
message = JSON.parse(message.data);
if(message.type === 'success'){
resolve(message.data);
} else {
reject(message.data);
}
document.body.removeChild(ifr);
});
});
};
关于javascript - 重试地理定位请求而不刷新浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381742/