To build a multilingual website, it is important to know language preferences
of users. There are two ways for frontend programmers to detect browser language
preference:
- Via NavigatorLanguage API: This API contains properties (language and
languages) to indicate the preferred language of the browser user. This post
will mainly focus on how to use this API.
- Via Accept-Language header in HTTP request: There is no way to directly
access this header in your code. You can, however, run a server which returns
the headers to client browser via JSONP. See for more details.
navigator.language returns the preferred language of the user, while
navigator.languages returns languages known to the user.
console.log(navigator.language);
console.log(navigator.languages);
The return value of navigator.language is string, and the return value of
navigator.languages is an array.
The above code in Go/GopherJS is as follows:
import (
"github.com/gopherjs/gopherjs/js"
)
println(js.Global.Get("navigator").Get("language").String())
println(js.Global.Get("navigator").Get("languages").String())
Run Code on GopherJS Playground
Note that the return value of both are strings because of the constraint of
GopherJS compiler.
To make your code more readable, we can prettify the above code with godom:
import (
. "github.com/siongui/godom"
)
println(Window.Navigator().Language())
println(Window.Navigator().Languages())
The full code example of this post is on my GitHub.
References: