Check client language with Javascript

It is simple enough to detect the end-users preferred language:

var language = window.navigator.userLanguage || window.navigator.language;

This will be a country code, for example ‘it’ or ‘en-US’

Example

This particular example uses the Google Translate service and will trigger the translate widget to show up if their language is different from your target language:

[raw]

<code>
&lt;div id="google_translate_element"&gt;&lt;/div&gt;
function googleTranslateElementInit() {
	new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT, gaTrack: true, gaId: 'UA-YOUR-GA-ID'}, 'google_translate_element');
}

// detect language and conditionally call the googleTranslateElementInit() function
var checkLanguage = function(){
	var TARGET_LANGUAGE = 'en-US',
	    language = window.navigator.userLanguage || window.navigator.language;
	if(language != TARGET_LANGUAGE){
		googleTranslateElementInit();
	}
};
&lt;/script&gt;&lt;script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=checkLanguage"&gt;&lt;/script&gt;
</code>

[/raw]

Leave a Reply