get country name from browser javascript

Get Country Name from Browser JavaScript

If you want to get the country name of the user who is visiting your website, you can use JavaScript to do so. There are a few ways to do this, and I'll explain them below:

Method 1: Using a Third-Party API

One way to get the country name is by using a third-party API. There are many APIs available that provide this information, such as ipapi, ipinfo, and ipstack. These APIs usually require an API key or subscription, but they offer more than just the country name, such as the city, region, and latitude/longitude.


fetch('https://ipapi.co/json/')
    .then(response => response.json())
    .then(data => {
        const countryName = data.country_name;
        document.getElementById('countryName').innerText = countryName;
    });

The above code fetches data from the ipapi API and extracts the country_name property from the response. It then sets the text of an HTML element with an ID of countryName to the country name.

Method 2: Using the Geolocation API

Another way to get the country name is by using the Geolocation API, which is built into most modern browsers. This API allows you to get the user's latitude and longitude, which you can then use to look up their country name using a database or service such as Nominatim.


if ('geolocation' in navigator) {
    navigator.geolocation.getCurrentPosition(position => {
        const {latitude, longitude} = position.coords;
        fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`)
            .then(response => response.json())
            .then(data => {
                const countryName = data.address.country;
                document.getElementById('countryName').innerText = countryName;
            });
    });
}

The above code checks if the browser supports the Geolocation API and gets the user's current position. It then fetches data from the Nominatim API using the latitude and longitude, and extracts the country property from the response. It sets the text of an HTML element with an ID of countryName to the country name.

Method 3: Using the User-Agent String

Finally, you can get the country name by parsing the user-agent string of the browser. This method is less accurate than the previous two methods, as the user-agent string can be spoofed or modified, but it can still provide useful information.


const userAgent = navigator.userAgent;
const matches = userAgent.match(/(cfnetwork|Darwin|Windows|Linux)[^;]*;.*?(?:iPhone|iPad)?.*?Version\/\d+\.\d+\.\d+.*?Safari/);

if (matches) {
    const platform = matches[1];
    const isiOS = /iPhone|iPod|iPad/.test(userAgent);
    let countryName;

    if (isiOS) {
        const regionCode = window.navigator.language.split('-')[1];
        countryName = Intl.DisplayNames(['en'], {type: 'region'}).of(regionCode);
    } else if (platform === 'Windows') {
        countryName = userAgent.match(/Windows NT \d+\.\d+; ([^)]+)/)[1];
    } else if (platform === 'Linux') {
        countryName = userAgent.match(/Linux.*?\((.*?)\)/)[1];
    }

    document.getElementById('countryName').innerText = countryName;
}

The above code extracts the user-agent string from the browser and searches for patterns that indicate the platform and browser version. It then uses this information to determine the user's country name, either by using the Intl.DisplayNames API for iOS devices or by extracting the country name from the user-agent string for Windows and Linux devices.

  • Method 1: Use a third-party API, such as ipapi or ipinfo
  • Method 2: Use the Geolocation API and a database or service, such as Nominatim
  • Method 3: Parse the user-agent string of the browser to determine the platform and browser version, then use this information to determine the user's country name

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe