JavaScript to detect OS in Chrome Version 37.0.2062.94

327 views Asked by At

I'm developing one-page apps. The shortcut should vary from different OSs, especially Mac OS X. Others usually combine keystroke with Ctrl, but Mac combins with Cmd.

Until now, I tried to detect whether the OS is mac or not by this code:

var bMac = navigator.appVersion.indexOf('Mac') > -1;

This code worked well. However, after updating the Chrome to the recent version (37.0.2062.94), it doesn't work anymore.

Is there anyway to detect host OS of browser in JavaScript?

I checked Google Docs in Chrome and it's shortcut worked well with Cmd in Mac and Ctrl in Window. There should be a way to detect OS in JavaScript in Chrome.

EDIT I googled and found some pages about detecting OS in javascript:

2

There are 2 answers

0
ntalbs On BEST ANSWER

It seems that there were some unexpected side effect while upgrading the version. It's still hard to understand.

When I checked the navigator.appVersion, it looked strange that there was Linux; Android....

> navigator.appVersion
  "5.0 (Linux; Android 4.2.2; GT-I9505 Build/JDQ39) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.59 Mobile Safari/537.36"

I checked the Emulation tab in the developer tools, and it looked like this: enter image description here

It was strange that this tab was usually empty. Anyway after I clicked Reset button in the tab, it come back.

> navigator.appVersion
  "5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"
0
goerwin On

With navigation.userAgentyou should good to go, but you have to parse the response. This is a very good small javascript to detect OS, browser, device, device version, etc. By adding classes to the html tag. It's intended to help you with css styles but it have other uses as well.

Example, after running that small javascript you'll have:

<html class="webkit chrome mac">