javascript 当用户允许或拒绝访问“物理位置”时如何调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7463367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call function when user Allows or Denies access to "Physical Location"?
提问by edt
My application is powered by jQuery mobile and uses geolocation.
我的应用程序由 jQuery mobile 提供支持并使用地理定位。
After my application attempts to get the user's location, the (Chrome) browser prompts the user:
在我的应用程序尝试获取用户的位置后,(Chrome)浏览器会提示用户:
Example.com wants to track your physical location [allow] [deny]
Example.com 想要跟踪您的物理位置 [允许] [拒绝]
My goal is:
我的目标是:
- If the user clicks "Allow", function 1 is called (location is used by app).
- If the user clicks "Deny", function 2 is called (address form appears).
- 如果用户单击“允许”,则调用函数 1(应用程序使用位置)。
- 如果用户单击“拒绝”,则调用函数 2(显示地址表)。
How can I bind a function to the event that occurs (if any) when the user clicks the "Allow" or "Deny" button?
当用户单击“允许”或“拒绝”按钮时,如何将函数绑定到发生的事件(如果有)?
回答by pimvdb
The getCurrentPosition
function accepts two function arguments. Heck, the first is executed when you allow and the other when you deny!
该getCurrentPosition
函数接受两个函数参数。哎呀,第一个在您允许时执行,另一个在您拒绝时执行!
http://jsfiddle.net/pimvdb/QbRHg/
http://jsfiddle.net/pimvdb/QbRHg/
navigator.geolocation.getCurrentPosition(function(position) {
alert('allow');
}, function() {
alert('deny');
});
回答by Waheed Akhtar
function handlePermission() { navigator.permissions.query({name:'geolocation'}).then(function(result) {
if (result.state == 'granted') {
report(result.state);
geoBtn.style.display = 'none';
} else if (result.state == 'prompt') {
report(result.state);
geoBtn.style.display = 'none';
navigator.geolocation.getCurrentPosition(revealPosition,positionDenied,geoSettings);
} else if (result.state == 'denied') {
report(result.state);
geoBtn.style.display = 'inline';
}
result.onchange = function() {
report(result.state);}});}function report(state) {
console.log('Permission ' + state);}
I hope this works.
我希望这有效。