Permission for geolocation must be granted every time when using Safari and mobile browsers

My website requests geolocation permission but has a recurring issue. When accessed on mobile (using Chrome or Safari) or desktop Safari, the permission prompt pops up every time a page is reloaded.

However, when accessing the site on a computer with Chrome, everything works flawlessly.

I've included my code below. Can you help me identify the cause of this problem?

jQuery(document).ready(function($) {
    if ("geolocation" in navigator) {
        console.log("Geolocation available");
        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);
            }
        })
    }
});

Answer №1

The timing of when a browser requests permission for geolocation can vary depending on the specific browser being used.

Typically, most modern browsers will prompt the user for permission with each individual use of geolocation services, unless the user opts to save their decision for future references.

For web applications, it is recommended to refrain from making unsolicited geolocation requests and instead allow the user to initiate the action by clicking a designated button.

If this approach does not align with your requirements, you have the option to store the result of the initial successful geolocation request (e.g., in a cookie or localStorage) and utilize it while the user is active on your site.

Here's an example demonstrating this concept:

function onLocationFound(coordinates) {
  console.log('The user was located at:', coordinates)
}

function locationError() {
  console.log('Unable to determine location.')
}

function locationSuccess(position) {
  const coordinates = {
    lat: position.coords.latitude,
    lng: position.coords.longitude
  }

  document.cookie = 'geolocation=' + JSON.stringify(coordinates)

  onLocationFound(coordinates)
}

const storedLocationString = document.cookie
  .split('; ')
  .find(function (cookiePair) {
    return cookiePair.startsWith('geolocation=')
  })
  ?.split('=')[1]

if (storedLocationString) {
  const coordinates = JSON.parse(storedLocationString)
  onLocationFound(coordinates)
} else if ("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
} else {
  locationError()
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP is not receiving any data from the Ajax request

I'm currently attempting to set up my first Ajax example on my MAMP server. Here's how my ajax.html file looks: <html> <head> <script src='ajax.js'></script> </head> <body onload = 'ajax()'> ...

Access to service is currently unavailable in REST API request made through WordPress

After setting up a basic installation of WordPress and WooCommerce, I developed a custom plugin that communicates with an API using the GET protocol and a bearer token. I successfully tested the PHP cURL code from Postman both locally and on Postman to con ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

Display HTML using JavaScript/jQuery

I am trying to figure out how to print a document by passing custom HTML code. Below is the code I have tried, but unfortunately it's not working: function Clickheretoprint() { var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes, ...

Guide on accessing the fastify application instance within an imported module

Currently, I am working on developing a rest API using Fastify and I am in the process of organizing my code into separate files for better structure. One issue I am facing is how to access the Fastify instance within a file that I import. The following s ...

Validating forms in express.js

I need to validate a form that includes user details. In addition to the basic validation for checking if fields are not empty, I also want to verify if the username/email exists in the database. For the email field, I need to ensure it is not empty, follo ...

Instructions for importing a CSV file into PostgreSQL with Node.js

Just dipping my toes into the world of node js. I've got a csv file sitting on my local system that I'm eager to upload to my local PostgreSQL Database using node js. Here's what I've been experimenting with: var csv = require(' ...

Sending a piece of state information to a different component

Hey, I'm a new React developer and I'm struggling with a particular issue. I've included only the relevant code snippets from my app. Basically, I want to retrieve the data from the clicked Datagrid row, send it to a Dialog form, and then p ...

Restrict User File Uploads in PHP

I have a system set up that enables users to upload files under 200 MB. Once the file is downloaded once, it will be automatically deleted. Additionally, all files are deleted from the server after 24 hours. I am looking for a way to limit the number of up ...

Dealing with HTML fields that share the same name in various positions can be tricky

Currently, I have developed a non-commercial web application using basic HTML, PHP, and Javascript along with Dynamic Drive's Tab Content code. This app serves as a tool for managing the books in my home library as well as on my ereader. My main goal ...

Tips for showing multiple autocomplete entries in a text box following a successful AJAX request

I'm having an issue with my code where the autocomplete multiple values, successfully retrieved by Ajax, are not being displayed. Here is the HTML I am using for display: <input type="text" name="s_to" id="s_to" class="controls"> Here is my jQ ...

In JavaScript, creating a new array of objects by comparing two arrays of nested objects and selecting only the ones with different values

I've been struggling to make this work correctly. I have two arrays containing nested objects, arr1 and arr2. let arr1 =[{ id: 1, rideS: [ { id: 12, station: { id: 23, street: "A ...

Obtain the unique identifier of the chosen option using material-ui's autocomplete feature

I am currently implementing the autocomplete feature using material-ui. The data in the "customerList" displayed in the search field works fine. However, I am facing an issue with retrieving the "ID" number of the selected data. My goal is to obtain the ID ...

Sketch a line extending from one element to the next

Is there a way to create a styled line that starts from the center of one <td> element and ends at the center of another? I attempted to use the jQuery Connections plugin but it only connects the edges of the elements, not their centers. The plugin ...

Popovers in Bootstrap 4 do not have clickable Custom Forms

I find it strange that in Bootstrap 4, only custom forms are not clickable in the Bootstrap popover. It's interesting how default forms in Bootstrap 4 work just fine. Any suggestions on how to resolve this issue? Below is my code. Thank you for you ...

Loop through a JSON object to dynamically update the value of a specific key

I have a JSON object with keys and values, where some of the values are empty strings. I want to replace those empty values with the corresponding key name. However, when trying to get the value of a key within the loop, it returns undefined. JSON: "Forg ...

Are you utilizing Google Chrome extensions for importing and exporting JSON files?

Currently, I am in the process of developing a Google Chrome extension and I have a question regarding its capabilities. Is it possible for the extension to generate JSON files for users to download (export) as well as implementing a button that allows use ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

The alterations made to a single dropdown option are causing ripple effects across all other dropdowns

There is an add button that continuously adds a div container containing two dropdowns. The selection in one dropdown affects the data in the other dropdown. When the add button is clicked, a second div with both dropdowns is added. However, changing the ...

Observing a global object's attribute in Angular JS

Imagine you have an object in the global scope (yes, I know it's not ideal but just for demonstration purposes) and you wish to monitor a property of that object using Angular JS. var person = { name: 'John Doe' }; var app = angular.mod ...