[Golang] Detect Browser Language Preference by window.navigator.language


Introduction

To detect browser language preference (user locale), one of the solution is to access Accept-Language field in HTTP Request Header. We cannot, however, access the Accept-Language in our browser code. One of the answers in Stack Overflow question [4] provides an alternative - use NavigatorLanguage API. This API provides you the same information of preferred language of the user. This post shows you how to access window.navigator.language and window.navigator.languages in Go.

Install GopherJS

Run the following command to install GopherJS:

$ go get -u github.com/gopherjs/gopherjs

Source Code

HTML file for demo: (index.html)

<!doctype html>
<html>
<head>
  <title>Golang - access window.navigator.language
         to detect browser language preference</title>
</head>
<body>
<script src="demo.js"></script>
</body>
</html>

js.Global object is equivalent to window object in browsers. The Get method is used to access the property of the object.

Run Code on Gopherjs Playground

language.go | repository | view raw
1
2
3
4
5
6
7
8
9
package main

import "github.com/gopherjs/gopherjs/js"

func main() {
	println(js.Global.Get("navigator").Get("language"))
	println(js.Global.Get("navigator").Get("languages"))
	println(js.Global.Get("navigator").Get("onLine"))
}

Compile Go code to JavaScript by:

$ gopherjs build language.go -o demo.js

Put demo.js together with the index.html in the same directory. Open the index.html with your browser, and then open the browser console to see the result.


Tested on: Ubuntu Linux 15.10, Go 1.5.3, Chromium Version 47.0.2526.106 Ubuntu 15.10 (64-bit).


References:

[1]GopherJS - A compiler from Go to JavaScript (GitHub, GopherJS Playground, godoc)
[2]Bindings · gopherjs/gopherjs Wiki · GitHub
[3]dom - GopherJS bindings for the JavaScript DOM APIs (GitHub)
[4]localization - JavaScript for detecting browser language preference - Stack Overflow
[5]Navigator - Web APIs | MDN