10

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
edt
  • 22,010
  • 30
  • 83
  • 118
  • You can probably not bind anything to those buttons, but what does the function you call return when you click "deny"? – Pekka Sep 18 '11 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 Sep 18 '11 at 18:21

2 Answers2

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');
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 5
    Is there an event that fires when the user simply dismisses the dialog or selects 'not now' (in Firefox), rather than clicking 'deny'? – Richard Ev Jan 16 '14 at 17:33
  • 3
    This does not work exactly. I wish it did. I get a few seconds of nothing before the event, or the alert in this example, fires. So, the user is left with no feedback for a few seconds which is bad... – Ronnie Royston May 06 '16 at 02:10
  • is there any event when one closes popup? no "allow", no "deny" anly popup is closed. – Amol Mar 27 '18 at 09:33
2

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.

Waheed Akhtar
  • 3,110
  • 1
  • 16
  • 30