The Navigator Object

By

Learn what the browser Navigator object is and how window.navigator exposes Web Platform APIs through properties like geolocation, language, and userAgent.

~~~

The window.navigator property exposed by browsers points to a Navigator object, a container object that makes a lot of Web Platform APIs available to us. It tells us about the browser and the environment the page runs in, and it’s the entry point for APIs like geolocation and service workers.

You can inspect it right now. Open the browser console and type navigator.

The standard and widely implemented properties include:

Some examples

language is handy when you want to greet users in their own language, or pick a default locale:

navigator.language // 'en-US'

onLine gives you a quick connectivity check:

if (!navigator.onLine) {
  console.log('You are offline')
}

Remember the warning above: true only means the device has some network connection. It does not guarantee the internet is actually reachable.

geolocation is the entry point of the Geolocation API. This asks the user for permission, then gives you their coordinates:

navigator.geolocation.getCurrentPosition(position => {
  console.log(position.coords.latitude, position.coords.longitude)
})

It only works on pages served over HTTPS (or on localhost).

Be careful with userAgent

userAgent returns a string like this:

navigator.userAgent
// 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 ...'

It’s tempting to parse this string to detect which browser is visiting your site, then branch your code on it. Don’t.

The string is famously misleading (notice every browser claims to be Mozilla), and browsers have been freezing and reducing parts of it over time. Code that sniffs the user agent breaks when browsers update.

The fix is feature detection: check if the API you need exists, instead of guessing from the browser name:

if ('geolocation' in navigator) {
  //we can use the Geolocation API
}

Methods

The standard methods include:

There are many more methods and properties which are provided by APIs that are either experimental or implemented as drafts and not yet finalized, or just available on a tiny fraction of browsers, so I haven’t included them here but you can explore them all on MDN.

~~~

Related posts about platform: