Reputation: 7
I want a javascript file (<script src=" file here " >
) to be hidden if a user lets say comes from China.
How can i do it?
Upvotes: 0
Views: 241
Reputation: 2535
I'm Chinese and I reserve all my rights to protest. :)
Actually you have a few options, you can do it front-end or back-end.
Front-end solution
Use HTML5 Geolocation
to determine the longitude and latitude of current user and check whether it's within China or not(don't forget to contain Taiwan). The defect is only modern browsers are supported, you should probably set up plan B.
//jQuery, ip-api is a RESTful service, do it in front-end
$.getJSON('http://ip-api.com/json/?callback=?', function(response){
alert(response.country);
if(response.country === "China"){
$.getScript("script_for_Chinese.js");
}
});
Back-end solution
IP to location
RESTful services)Accept-Language
part contains string like zh-CN
or zh-TW
. This may also hurt the people using Chinese in other countries.As for example requested, I won't recommend you use front-end solution or IP-to-location
back-end solution. The only one that might work is based on http header.
//PHP, if the client accept Chinese, assume he is from China
if(preg_match('/(zh-CN|zh-TW|zh)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'])){
echo '<script src="script_for_Chinese.js" type="text/javascript"></script>';
}
Upvotes: 1
Reputation: 31644
You can try using a geolocation service but considering that you can defeat that by using a proxy (like a hacked machine in the US) somewhere else or by spoofing the request to look like it came from given location it may not do you much good in the end.
Upvotes: 1