My GeoLocation redirection code makes my website go in a infinite loading loop
This is the code for the geolocation
function redirectBasedOnLocation() {
// Make a request to the Geolocation API
fetch('https://ipapi.co/json/')
.then(response => response.json())
.then(data => {
const country = data.country_code;
// Check if the visitor is from India (country code: IN) if (country === 'IN' && !redirected) { redirected = true; // Redirect to the India-specific page window.location.href = 'indexi.html'; console.log("Hello") } }) .catch(error => { // Handle any errors that occur during the API request console.error('Error:', error); }); }
// Call the function when the page loads document.addEventListener('DOMContentLoaded', redirectBasedOnLocation); My website just keeps on loading and dosent end. Some one please help
// Check if the visitor is from India (country code: IN) if (country === 'IN' && !redirected) { redirected = true; // Redirect to the India-specific page window.location.href = 'indexi.html'; console.log("Hello") } }) .catch(error => { // Handle any errors that occur during the API request console.error('Error:', error); }); }
// Call the function when the page loads document.addEventListener('DOMContentLoaded', redirectBasedOnLocation); My website just keeps on loading and dosent end. Some one please help
4 Replies
that setting of
redirected
will get unset on the next page load. You can either store that in something more permanent like a cookie or localstorage, or just have the auto-redirect on index.html
and not on indexi.html
the idea here is to redirect my index page to indexi.html and the redirected variable could be stored in cookie but i tried it and didnt work
how did you store and retrieve the value?
(Also, just a point of flow critique: Unless you want to redirect people who have been redirected before if the country code doesn't match the current page, you should check if people have been redirected before checking where they are to save a call to the API)
Ok