Get Current User Language

How to get the current locale viewed by a user on run-time

Ishai Jaffe avatar
Written by Ishai Jaffe
Updated over a week ago

In many cases we would like to integrate your translated website with external or internal services, and we would like to know on which language the user have viewed your website.

Javascript API

If you need to get the current language on the client side, you Bablic Javscript API.

bablic.getLocale();
>> "fr"

This method will only work when placed after Bablic snippet. If you are placing this code before the Bablic snippet, it will crash. To prevent this, you can listen to bablicload event on document.

document.addEventListener('bablicload',function() {
    // this will print current locale code to console.
    console.log(bablic.getLocale());
});

Language can be changed by user

If you wish to get the most current language as soon as it changed, use the locale Bablic event.
This code will print the current language code immediately to console, and will do it also every time the language is changed by the user.

bablic.on('locale',function(languageCode) {
    console.log(languageCode);
});

Get Language By Cookie

Bablic sets the current language code in a public cookie named "bab_locale".
You can read this cookie on server or client side to get the current language code.

Did this answer your question?