Skip to content
the poor coder

get country name from browser javascript

Poor Man
Published
Reading time
3 min read
On this page

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.

Text

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.

Text

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.

Text

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

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC