Providing a fallback for Safari when querying Permissions API

October 31, 2021

The Permissions API is still not (at the time of writing) supported in Safari.

Querying the permissions status of some permission-based Web API, e.g. geolocation, is commonly done like so:

if (navigator?.permissions) {
      navigator.permissions
        .query({name:'geolocation'})
        .then((status) => {
          // do something with the status
        })
        .catch(...);
    }

However, with Safari this is not possible since the Permissions API is not supported. Instead, if we want to know whether or not a user has given access to geolocation data, we can work around this by making use of functionality provided by the API that we are querying the permission for. In this case, that'd be the navigator.geolocation API. The fallback could be along the lines of the follwong:

if (navigator?.geolocation) {
  navigator.geolocation.getCurrentPosition(
    () => {
      // success callback means permission granted
      // do something with success status
    },
    () => {
      // error callback means permission denied
      // do something with error status
    }
  );
}

This works since if navigator.gelocation.getCurrentPosition returns position data, we can be sure that permission has been granted.