Detecting Chrome OS with Javascript

*爱你&永不变心* 提交于 2019-12-02 04:08:23
T.J. Crowder

What it's complaining about is that you have an ( with no matching ). In a regular expression, ( and ) define capture groups and have to be balanced. If you want to match an actual ( or ), you have to escape it with a backslash.

But there are several other issues. It doesn't make sense to have ^ ("beginning of input") anywhere but the beginning of the expression, for instance.

But I don't think anything else puts CrOS in the user agent, so perhaps simply:

if (/\bCrOS\b/.test(navigator.userAgent)) {
    // yes, it is (probably, if no one's mucked about with their user agent string)
} else {
    // No, it isn't (probably, if no one's mucked about with their user agent string)
}

The \b are "word boundaries" so we don't match that string in the middle of a word. Note that I left it case-sensitive.


Side note: I find https://regex101.com/#javascript (which I am not in any way affiliated with) quite useful for debugging regular expressions.

Side note #2: The above is useful if you really do need to detect ChromeOS, but if it's just a feature you need to check for, as jfriend00 points out, feature detection may be the better way to go.

How about this?

var chromeOS = /(CrOS)/.test(navigator.userAgent);

Because a Chrome OS user agent looks like this:

Mozilla/5.0 (X11; CrOS i686 0.12.433) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.77 Safari/534.30

And filtering out "CrOS" is a good solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!