I'm building a small script that clients will install on their page. Geolocation is not necessary for it, however if it exists it would be nice to have. Is there a way for me to check if the clients page has requested geolocation information and if the user selected allow get the lat & lon without creating another prompt?
It isn't possible with the geolocation API but it is possible with the new permission API
This code is useful if you want to try to receive the coordinates but don't want to bother the user with a prompt dialog cuz the coordinates is not that important and may as well fallback to geoIP
function getCoords() {
return new Promise((resolve, reject) =>
navigator.permissions ?
// Permission API is implemented
navigator.permissions.query({
name: 'geolocation'
}).then(permission =>
// is geolocation granted?
permission.state === "granted"
? navigator.geolocation.getCurrentPosition(pos => resolve(pos.coords))
: resolve(null)
) :
// Permission API was not implemented
reject(new Error("Permission API is not supported"))
)
}
getCoords().then(coords => console.log(coords))
This will resolve to null if permission hasn't been granted, cast a error if some javascript code wasn't supported by the browser and resolve to the coordinates if it has been granted