6

Does anyone know if there is a way to test if prior html5 geolocation permission has been granted?

I try to make a script that does not request the geolocation unless the permission for the page has already been given. Does not nessicerily have to be html5; other frameworks are also ok.

RickyA
  • 15,465
  • 5
  • 71
  • 95

3 Answers3

11

The first part actually answers your question, at least on Chrome 43+ and Firefox 46+ (see https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API):

navigator.permissions &&
navigator.permissions.query({name: 'geolocation'}).then(function(PermissionStatus) {
    if('granted' === PermissionStatus.state) {
        navigator.geolocation.getCurrentPosition(function(geoposition) {
            console.log(geoposition) /* You can use this position without prompting the user if the permission had already been granted */
        })
    }
})
  • 1
    The best answer, but in Safari doesn't work navigator.permissions. Likewise, Thank you! – Carlos Galeano May 01 '19 at 17:11
  • It seems to be possible in Safari since Version 16.0 (released in Sep 2022). https://caniuse.com/?search=navigator.permissions – yunzen Jul 26 '23 at 12:32
2

Best you can do is to keep track of this yourself...

// In chrome you can now do this    
navigator.permissions.query({name: 'geolocation'}).then(function(PermissionStatus){
    console.log(PermissionStatus.state) // prompt, granted, denied
    // even listen for changes
    PermissionStatus.onchange = function(){
        console.log(this.state)
    }
})

fallback method:

// initialization
if( sessionStorage.getItem("geo_access") === null ){
    // just assume it is prompt
    sessionStorage.setItem("geo_access", "prompt");
}

function ask(){
    navigator.geolocation.getCurrentPosition(function(){
        sessionStorage.setItem("geo_access", "granted");

    }, function(err){
        if(err.code == 1){ // PERMISSION_DENIED
            sessionStorage.setItem("geo_access", "denied");
        }
        sessionStorage.setItem("geo_access", "prompt");
    });
};

// Then somewhere
ask();
Endless
  • 34,080
  • 13
  • 108
  • 131
0

According to the Geolocation API Specification there isn't any function for this. Even the option to save it in the browser preferences isn't pushed to your code.

If it's realy important and you realy have to beeing aware of this, you have to write a browser addon for every common browser and ask the user to install it. But i wouldn't doubt of it.

GodLesZ
  • 899
  • 5
  • 6