Skip to content

Instantly share code, notes, and snippets.

@javimata
Created August 25, 2021 17:32
Show Gist options
  • Save javimata/9c3b9a0add3f666a29dc63ead60dcc4b to your computer and use it in GitHub Desktop.
Save javimata/9c3b9a0add3f666a29dc63ead60dcc4b to your computer and use it in GitHub Desktop.
Check country for a visitor
/*
* Info of ip get with https://ipinfo.io/ service
* Free service have 50k request/month
* If have a user need use the url https://ipinfo.io/json?<YourToken>
*/
/*
* Function to create a cookie, need
* cname = Name of cookie
* cvalue = Value of cookie
* exdays = Life of cookie in days
*/
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
/*
* Get the cookie value
* cname = Name of cookie to check
* Return value or null string if not exist
*/
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i <ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
/*
* First check if the visitor isn't a bot, not wanna consume api request
* country is the name of cookie with info
* If cookie country not exist do a fetch to ipinfo.io to get visitor location information
* and create a cookie country with the value
*/
if( !navigator.userAgent.match(/bot|spider/i) ){
let country = getCookie("country");
if ( country == "" ) {
fetch('https://ipinfo.io/json')
.then( res => res.json())
.then( data => {
setCookie("country", data.country, 365);
}
);
}
}
// USING LOCALSTORAGE
/*
if( !navigator.userAgent.match(/bot|spider/i) ) {
if ( !localStorage.getItem('country') ) {
fetch('https://ipinfo.io/json')
.then(res => res.json())
.then(data => {
localStorage.setItem('country', data.country)
})
} else {
alert( localStorage.getItem('country') );
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment