javascriptpermissionsgeolocationw3c-geolocation

How to detect when user allows location in browser?


For a web Application, when the user makes a choice of radio button on a previous unrelated field, I am trigerring location for the next step by calling attemptLocation().

  const attemptLocation = () => {
    if ("geolocation" in navigator) {

The possible scenarios are:

  1. A popup appears in browser and user allows the location immediately - Works !
  2. The user clicks on 'Block' and location is not available. The user then realizes that they cannot proceed so they click on the location icon in browser and allow location.

How to detect this change they made from block to allow in the browser because right now

To simplify the question: After page loads, the user who blocked location, changes from block to allow location, how can I alert ("thanks for changing from block location to allow location") ?


Solution

  • Thanks to @GabrielePetrioli's comment. The code below uses navigator.permissions.queryPermissions Status Change Event

    I am checking if permission was granted and updating the application by calling the function which updates location.

    const [locationAccess, setLocationAccess] = useState(false);//user changes in browser
    ...
          //check user location changes in navigator
          navigator.permissions.query({ name: 'geolocation' }).then((permissionStatus) => {
           
              permissionStatus.onchange = () => {
              setLocationAccess(permissionStatus.state=="granted")
    
              if (permissionStatus.state=="granted") {
                  attemptLocation();
                }
              };
            });