detectmobilebrowser.js的正则表达式有魔力吗

Is there magic in the regular expression of detectmobilebrowser.js?

本文关键字:有魔力 正则表达式 js detectmobilebrowser      更新时间:2023-09-26

我已经阅读了Detect Mobile Browser的代码。

我对此感到困惑,希望有人能解释一下它是如何工作的:

(对不起,我只找到了一个最小化的版本,为了更好的可读性,我添加了一些换行符,希望不会破坏代码。)

(function (a,b) {
     if(/(android|bb'd+|meego).+mobile|avantgo|bada'/|blackberry
        |blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge
        |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?
        |phone|p(ixi|re)'/|plucker|pocket|psp|series(4|6)0|symbian|treo|up'.browser|link)
        |vodafone|wap|windows (ce|phone)| 
        ... and many more patterns ...
        |zeto|zte'-/i.test(a.substr(0,4)))
    window.location=b
})(
    navigator.userAgent || navigator.vendor || window.opera, // argument a
    'http://detectmobilebrowser.com/mobile'                  // argument b
);

我的问题是:

针对navigator.userAgentnavigator.vendorwindow.opera的前4个字符(第一个真值)测试正则表达式。

让我困惑的是:

  • 正则表达式的许多组件的长度远远超过4个字符
  • 我见过的大多数userAgent都像Mozilla/5.0 (Linux; U; Android 4.1.1; ...,所以在很多情况下,前4个字符都是"Mozi"

它是如何工作的?

我在Chrome控制台中的简单测试:

/android|blackberry/i.test('Mozilla/5.0 (Linux; U; Android 4.1.1; ...'.substr(0,4))
// -> false
/android|blackberry/i.test('Mozilla/5.0 (Linux; U; Android 4.1.1; ...')
// -> true

您被缩小的代码误导了。它实际上是这样的:

if (/(android|bb'd+|meego).../i.test(a) ||
    /1207|6310|6590|3gso.../i.test(a.substr(0, 4))) {
    window.location = b
}