How to get a user's system language in Electron?


#1

In a web app I can detect user language with accept-language , but in the electron app I want to show the localized menu when the app start, how could I do it?


#2

navigator.language ?


#4

Thanks.

In the web page(renderer process) use navigator.language to detecting is a good idea, but I mean how cloud do it in the main process.


#5

This seems to works, it’s more complicated on the server.

The complication seems to come from the fact usually locale is a browser thing.


#6

I use fake invisible window to obtaining language info before creating main window:

lang.js

var html = ` 
<!DOCTYPE html>
<html lang="cs"> 
   <head>
      <script>
         var ipc = require('ipc');    
         ipc.sendSync('get-language', navigator.language);
      </script>
   </head>
<body>
</body>
</html>`; 

exports.get = function(){  
   return new Promise(function(resolve, reject) {

       var BrowserWindow = require('browser-window');   
       var win = null;    
    
       win = new BrowserWindow({show: false});
    
       win.on('closed', function() {win = null;});
          
       var ipc = require('ipc');
       ipc.on('get-language', function(event, arg) {           
           if (win) win.close();
           resolve(arg);             
       });

       var url = 'data:text/html,' + html;           

       win.loadUrl(url);
  
   });   
}

and in main.js:

...
var mainWindow = null;

app.on('ready', appRun);

function appRun(){
  mainWindow = new BrowserWindow({width: 800, height: 600});
 
  var lang = require('./lang');   

  lang.get().then(function(val){
      console.log('LANG-INFO', val);
  }).then(function(){
      console.log('AFTER-LANG-INFO');
      mainWindow.loadUrl('file://' + __dirname + '/index.html');  
  });

  ...
}

#7

Thanks. I prefer the os-locale which @jeancroy suggested. Cause the os-locale detects OS language with process.env (in the Mac OS, didn’t test in Linux), and executing wmic > os get locale in the Windows.

But os-locale has a small problem for me, in the Windows system, if declare osLocale out of app.on('ready', function(){...}) like this:

const osLocale = require('os-locale');
...
app.on('ready', function(){...});

and in it like this:

app.on('ready', function(){
  const osLocale = require('os-locale');
  ...
});

I get two different results. I am trying to look for the reason then solving it.


#8

There’s a silent fallback to en_us instead of throwing error, maybe that’s what you see.
Also winXP is not supported, the wmi thing is not there I beleive.


#9

Electron now has a app.getLocale function that can do exactly what you want. see this link for detail.


#10

hi, if you declare 2 variables in different scope. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Just don’t mention const second time and you’ll have one variable.