http://web.archiveorange.com/archive/v/fwvde0wN3xcViMtADw6x
It seems that navigator.language property is always "en" in webview on androids. Then, what is the best way to get the language of user? Get it in native java code and pour it into webview by javascript? or any other better way?
The default Locale is constructed statically at runtime for your application process from the system property settings, so it will represent the Locale selected on that device when the application was launched.
The solution I found to this problem is to set the user agent through the webview's settings:
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
settings.setUserAgentString(Locale.getDefault().getLanguage());
In your webcontent you then retrieve it through:
var userLang = navigator.userAgent;
This should only be used for a webview displaying local content.
One way to solve this is to take the userAgent - navigator.userAgent
, and run a regex on it looking for the language.
Example Android ua string (from http://www.gtrifonov.com/2011/04/15/google-android-user-agent-strings-2/):
Mozilla/5.0 (Linux; U; Android 2.0.1; en-us; Droid Build/ESD56) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17
so just match for the language: navigator.userAgent.match(/[a-z]{2}-[a-z]{2}/)
, which returns en-us
If you want to be really safe, you can match for the presence of Android 2.0.1;
immediately preceding the language. The regex for that would be:
navigator.userAgent.match(/Android \d+(?:\.\d+){1,2}; [a-z]{2}-[a-z]{2}/).toString().match(/[a-z]{2}-[a-z]{2}/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With