Search code examples
javascriptwordpressgeolocation

Geolocation Permission asked every time on Safari and mobile browsers


I have a website that asks for geolocation. It should only ask the first time you open the website but I noticed that if you open the website on mobile (with Chrome or Safari) or on desktop with Safari, the website asks for permission every time you reload a page.

If you open the website on a computer with Chrome it works as it should without any problems.

This is my code. What is the cause of this issue?

jQuery(document).ready(function($) {
    if ("geolocation" in navigator) {
        console.log("Geolocation availbale");
        navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
    } else {
        geolocationError()
    }

    function geolocationSuccess(position) {
        console.log(position.coords.latitude, position.coords.longitude);
        $.ajax({
            url: geolocationParams.ajaxurl,
            type: 'POST',
            data: {
                action: geolocationParams.actionLocalities,
                lat: position.coords.latitude,
                lng: position.coords.longitude,
            },
            dataType: 'json',
            success: function(response) {
                console.log("Ajax returned", response);
                $('.homepage-posts-wrapper.third-block-grid').html(response.html);
            }
        })
    }

    function geolocationError(err) {
        console.log(err);
        $.ajax({
            url: geolocationParams.ajaxurl,
            type: 'POST',
            data: {
                action: geolocationParams.actionLocalities,
                    lat: "",
                    lng: "",
            },
            dataType: 'json',
            success: function(response) {
                console.log("Ajax returned", response);
                $('.homepage-posts-wrapper.third-block-grid').html(response.html);
            }
        })
    }
});

Solution

  • When a browser decides to ask for permission is totally up to the browser and it differs.

    Most browsers nowadays will ask for each single usage, unless the user clicks "Remember this decision" in the dialog (example on Firefox):

    Geolocation permission dialog on Firefox

    Best practice for web apps is thus to not do unsolicited geolocation requests but instead let the user initiate the action by clicking a button.

    If that does not fit your use case, you could save the result of your first successful geolocation request (for example, in a cookie or localStorage) and use it while the user is on your site.

    Example (I am trying to stick to your style):

    function onWeHaveALocation(latLng) {
      console.log('Now or not too long ago the user was here:', latLng)
    }
    
    function geolocationError() {
      console.log('Location unknown.')
    }
    
    function geolocationSuccess(position) {
      const latLng = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }
    
      // This is a session cookie. Check the API for different lifetimes.
      document.cookie = 'geolocation=' + JSON.stringify(latLng)
    
      onWeHaveALocation(latLng)
    }
    
    // You might prefer to use a library like https://www.npmjs.com/package/js-cookie instead
    const geolocationCookieString = document.cookie
      .split('; ')
      .find(function (cookieKeyValuePair) {
        return cookieKeyValuePair.startsWith('geolocation=')
      })
      ?.split('=')[1]
    
    
    if (geolocationCookieString) {
      const latLng = JSON.parse(geolocationCookieString)
      onWeHaveALocation(latLng)
    } else if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
    } else {
      geolocationError()
    }