使用 Javascript 检测 Chrome 操作系统 [英] Detecting Chrome OS with Javascript

查看:34
本文介绍了使用 Javascript 检测 Chrome 操作系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 Javascript 检测 Chrome 操作系统,为此我使用了 navigator.userAgent.现在,我正在运行 Chrome 操作系统,而我的导航器 userAgent 是

I want to detect Chrome OS with Javascript, and I'm using navigator.userAgent for this. Now, I'm running Chrome OS, and my navigator userAgent is

Mozilla/5.0 (X11; CrOS armv7l 6680.78.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.102 Safari/537.36

现在.我使用正则表达式来检查 userAgent 的样式,并编写了下面的代码.

Now. I used Regular Expressions to check for the style of the userAgent, and wrote the code below.

<script>
    if ( navigator.userAgent = /^Mozilla\/\d{1}^.\d{1}^(X11; CrOS i\d{3} \d{1}^.\d{2}\d{3} ^AppleWebKit\/\d{3}^.\d{2} ^(KHTML, like Gecko) Chrome\/ \d{2}^.\d{1}^.\d{3}^.\d{2} ^Safari\/\d{3}^\d{2}/ ){
      console.log(navigator.userAgent);
    } else {
      console.log(navigator.userAgent);
    }
</script>

现在,在加载此脚本时,出现错误.

Now, upon loading this Script, I get an error.

Uncaught SyntaxError: Invalid regular expression: /^Mozilla\/\d{1}^.\d{1}^(X11; CrOS i\d{3} \d{1}^.\d{2}\d{3} ^AppleWebKit\/\d{3}^.\d{2} ^(KHTML, like Gecko) Chrome\/ \d{2}^.\d{1}^.\d{3}^.\d{2} ^Safari\/\d{3}^\d{2}/: Unterminated group

我的代码有什么问题?

推荐答案

它抱怨的是你有一个 ( 没有匹配的 ).在正则表达式中,() 定义了捕获组,并且必须平衡.如果你想匹配一个实际的 (),你必须用反斜杠将它转义.

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.

但我认为没有其他任何东西会将 CrOS 放入用户代理中,所以也许只是:

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)
}

\b 是单词边界",因此我们不匹配单词中间的字符串.请注意,我将其区分大小写.

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.

旁注:我发现 https://regex101.com/#javascript(我不在以任何方式附属)对于调试正则表达式非常有用.

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

旁注 #2:如果您确实需要检测 ChromeOS,则上述内容很有用,但如果它只是您需要检查的功能,如 jfriend00 指出,特征检测可能是更好的方法.

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.

这篇关于使用 Javascript 检测 Chrome 操作系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆