views:

53

answers:

2

I want to run a bit of code if, and only if, a visitor is from a certain country, is this possible and how would i go about doing this?

A: 

If you are able to detect user language / country server side, you may assign that information as a variable in javascript so you can run specific function then. Something more?

Tomasz Kowalczyk
+2  A: 

It's not possible with any certainty, but there are a couple of things that can be used as hints towards a visitor's country of origin:

  • The Accept-Language HTTP header tells you (if present) which language the user prefers to see - of course users can set this to whatever they want, and languages do not map 1:1 to countries.
  • There are also a number of Javascript objects that tell you which language the user's browser and OS use; same caveats as above.
  • There are a number of IP Geolocation services that you can use to derive a geographic location from the user's IP address. But these can sometimes yield no results or false results, and I'm not sure whether any of them are free to use.
Michael Borgwardt
About points 1 and 2, I would say languages rarely map 1:1 (I am not sure there is even one example).. And not only do they map really bad, people will most certainly use a navigator and OS in their favourite language, so a Chinese using Chinese as its language won't necessarily be in China at the moment.
Shautieh
Accept-language is useless for anything other than selecting the language for messages - even for languages which can be assigned to a single country, a lot of people set their browser to English anyway, because English interfaces tend to be better quality or have more features.
Tgr
@Shautieh: Japanese would be an example. As for people's settings, it's usually a good idea to respect them. Of course we don't know what David actually wants to do, but few things are more annoying than websites that insist on e.g. showing you the French version despite you being Chinese, using a Chinese browser and OS, just because you happen to be on a business trip to France.
Michael Borgwardt