Issue
When the page loaded, after adding the query parameter to the URL, I redirected to that URL.
However, an infinite loop occurs.
How can I implement this so that when the page is loaded, the value is sent from the JS to Rails and does not cause an infinite loop?
Code
window.onload = () => {
function successGetPosition(position) {
sessionStorage.setItem('latitude', position.coords.latitude);
sessionStorage.setItem('longitude', position.coords.longitude);
window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
}
function failGetPosition(error) {
...
}
options = {enableHighAccuracy: true};
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successGetPosition, failGetPosition, {enableHighAccuracy: true});
} else {
alert("Geolocation is not supported by this browser.");
}
}
getLocation();
};
CodePudding user response:
Inside this function, the first thing you should do is check if the url contains latitude, longitude query params in it.
function successGetPosition(position) {
// parse the url looking for latitude and longitude params
// if they are there, return immediately else proceed with the code below
const [latitude, longitude] = myUrlParseFn();
if (latitude && longitude) return;
sessionStorage.setItem('latitude', position.coords.latitude);
sessionStorage.setItem('longitude', position.coords.longitude);
window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
}