最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to call function when user Allows or Denies access to "Physical Location"? - Stack Overflow

programmeradmin1浏览0评论

My application is powered by jQuery mobile and uses geolocation.

After my application attempts to get the user's location, the (Chrome) browser prompts the user:

Example wants to track your physical location [allow] [deny]

My goal is:

  1. If the user clicks "Allow", function 1 is called (location is used by app).
  2. If the user clicks "Deny", function 2 is called (address form appears).

How can I bind a function to the event that occurs (if any) when the user clicks the "Allow" or "Deny" button?

My application is powered by jQuery mobile and uses geolocation.

After my application attempts to get the user's location, the (Chrome) browser prompts the user:

Example.com wants to track your physical location [allow] [deny]

My goal is:

  1. If the user clicks "Allow", function 1 is called (location is used by app).
  2. If the user clicks "Deny", function 2 is called (address form appears).

How can I bind a function to the event that occurs (if any) when the user clicks the "Allow" or "Deny" button?

Share Improve this question edited Sep 5, 2019 at 7:22 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Sep 18, 2011 at 18:11 edtedt 22.4k32 gold badges85 silver badges119 bronze badges 2
  • You can probably not bind anything to those buttons, but what does the function you call return when you click "deny"? – Pekka Commented Sep 18, 2011 at 18:14
  • When "deny" is clicked, the user is transferred to a page where they should fill in their address. The address is then sent to a web service that returns the geolocation. – edt Commented Sep 18, 2011 at 18:21
Add a comment  | 

2 Answers 2

Reset to default 23

The getCurrentPosition function accepts two function arguments. Heck, the first is executed when you allow and the other when you deny!

Documentation

http://jsfiddle.net/pimvdb/QbRHg/

navigator.geolocation.getCurrentPosition(function(position) {
    alert('allow');
}, function() {
    alert('deny');
});

Link to Docs

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.

发布评论

评论列表(0)

  1. 暂无评论