javascriptbrowserlocationuser-permissionsnavigator

How to detect timeout of user location permission if user didn't make decision after 3 seconds?


I want to do tasks after the user makes no decision on the location's permission. I have tried the following:

navigator.geolocation.getCurrentPosition((pos) => {
    let lat = pos.coords.latitude;
    let long = pos.coords.longitude;
    console.log(lat, long);
    console.log("User granted permission");
}, (error) => {
    console.error(error);
    console.error("User didn't grant permission");
}, {
    timeout: 3000,
    maximumAge: 3000,
    enableHighAccuracy: true
});

I have set timeout and maximumAge attributes to 3000 ms, but it didn't work anymore. The error will only be triggered if the user closes the permission pop-up. How can I detect if the user makes no decision after 3 seconds? Thank you.


Scenario:

  1. Website is opened by user -> Location alert appears -> user didn't click Allow or Block for up to 3 seconds -> Save dummy data location to database.
  2. Website is opened by user -> Location alert appears -> user click Allow before 3 seconds -> Save user data location to database.
  3. Website is opened by user -> Location alert appears -> user click Block before 3 seconds -> Save dummy data location to database.

Constraints:


Solution

  • I think Promisification of our geolocation API would be a great solution in this case.

    const getPosition = function () {
      // this will return a new Promise which will then give us Position when it's fulfilled
      return new Promise(function (resolve, reject) {
        // solution-1: more simplified version
        navigator.geolocation.getCurrentPosition(resolve, reject);
    
        // solution-2:
        // navigator.geolocation.getCurrentPosition(
        //   position => resolve(position),
        //   err => reject(err)
        // );
      });
    };
    
    // Simple Timeout function
    const timeout = function (sec) {
      // Here we just want to reject our promise so we can neglect resolve by replacing it with '_'
      return new Promise(function (_, reject) {
        setTimeout(function () {
          reject(new Error('Request took too long!'));
        }, sec * 1000);
      });
    };
    
    
    // Promise.race accepts array of Promise and return the first fulfilled promise
    Promise.race([getPosition(), timeout(3)])
      .then(pos => {
         let lat = pos.coords.latitude;
         let long = pos.coords.longitude;
         console.log(lat, long);
         console.log('User granted permission');
      })
      .catch(error => {
         console.error(error);
         console.error("User didn't grant permission");
      });

    Have more reading on