Drupal - Get current language of Drupal 8 in javascript?

In pages with the core/drupalSettings library included, it seems to be pretty reliably available through the path:

var langCode = drupalSettings.path.currentLanguage;

You can add whatever you want to the javascript via your THEMENAME.theme:

function THEMENAME_preprocess_page(array &$variables) {
    $variables['#attached']['drupalSettings']['language'] = $language;
}

After that, you can call it in javascript:

console.log(drupalSettings.language);

Edit

You need to enable drupalSettings as a dependency in your THEMENAME.libraries.yml:

frontend:
  dependencies:
    - core/drupalSettings

Tags:

Javascript

8