6

I have seen similar questions like below. But none of them works for me. Please help. Find the three letter country code using HTML and Javascript

How to find the operating system version using JavaScript

Community
  • 1
  • 1
David John
  • 55
  • 4

2 Answers2

6

There were some security features adopted by the browser to stop JavaScript getting the user's location without their consent. Now, you can use the following code to get the user's location. It will open a prompt window for the user to allow getting his/her location.

var recieveLocation = function(pos) {
    console.log(pos); // Latitude and Longitude Info 
}

navigator.geolocation.getCurrentPosition(recieveLocation);

The code above will return the user's geolocation. You will need to decode those longitude and latitude using the third party service to get the country information.

For an example, check Google Map Geocoding services API:
https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

Note: Most web browsers will need HTTPS to run the code. Check the console for the error message. For Mozilla Firefox, it will say:

[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS.

You will need to install the SSL certificate on the domain so the browser can trust on the website to allow getting the user's geolocation.

Pang
  • 8,605
  • 144
  • 77
  • 113
Navneet Singh
  • 1,108
  • 9
  • 16
0

navigator.language string contains a "county code".

navigator.platform string contains operating system and computer processor type.

Both can be spoofed.

An alternative approach would be to utilize html form to ask user what "country" they are currently reside in or identify with.

guest271314
  • 1
  • 10
  • 82
  • 156
  • navigator.language will not return the country code. it will just return the language setting of system. – Navneet Singh Apr 29 '17 at 03:00
  • @NavneetSingh `en-US` is a "code" not a "country". Note, a "country" can have "territories", which can, and do, extend beyond "their borders". What is definition of "country" here, at present Question? "Country code" or de jure original nation? Corporate entity or Original People of the Land? What is OP trying the achieve? Be _certain_ , _using `javascript`_ as part of requirement, that a network node is within a specific landmass and is using a specific processing microchip? Search for "browser fingerprinting" at SO and meta SO – guest271314 Apr 29 '17 at 03:04