Skip to content

Instantly share code, notes, and snippets.

@seanmars
Created May 22, 2020 07:03
Show Gist options
  • Save seanmars/cbf9a12533bb1edf04681515d1c43817 to your computer and use it in GitHub Desktop.
Save seanmars/cbf9a12533bb1edf04681515d1c43817 to your computer and use it in GitHub Desktop.
How to detect the location of your website's users with Javascript for free?
//regular expressions to extract IP and country values
const countryCodeExpression = /loc=([\w]{2})/;
const userIPExpression = /ip=([\w\.]+)/;
//automatic country determination.
function initCountry() {
return 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],
"IP": ip[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();
});
}
// Result {"countryCode":"SK","IP":"xxx.xxx.xxx.xxx"}
initCountry().then(result => console.log(JSON.stringify(result))).catch(e => console.log(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment