Hi,
I am using IP geolocation javascript. When I use this code, there is only one domain and 4 subdomains.
Naturally, when I use this code and go to other page, the page is constantly refreshed.
How can I prevent this code from working all the time.
Javascript
<script>
//regular expressions to extract IP and country values
const countryCodeExpression = /loc=([\w]{2})/;
const userIPExpression = /ip=([\w\.]+)/;
//automatic country determination.
function initCountry() {
var promise = new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.timeout = 3000;
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
countryCode = countryCodeExpression.exec(this.responseText)
ip = userIPExpression.exec(this.responseText)
if (countryCode === null || countryCode[1] === '' ||
ip === null || ip[1] === '') {
reject('IP/Country code detection failed');
}
let result = {
"countryCode": countryCode[1]
};
resolve(result)
} else {
reject(xhr.status)
}
}
}
xhr.ontimeout = function () {
reject('timeout')
}
xhr.open('GET', 'https://www.cloudflare.com/cdn-cgi/trace', true);
xhr.send();
});
return promise;
};
</script>
<script>
initCountry().then(function (result) {
if (result.countryCode == "DE") {
window.location.href = "https://de.site.com"
}
else if (result.countryCode == "NL") {
window.location.href = "https://nl.site.com"
}
else if (result.countryCode == "FR") {
window.location.href = "https://fr.site.com"
}
else {
window.location.href = "https://gl.site.com"
}
});
</script>