服务器端浏览器检测?节点.js

发布于 11-10 13:14 字数 73 浏览 3 评论 0原文

我见过的大多数实现都是用于客户端的浏览器检测。我只是想知道在向客户端发送任何资源之前是否可以进行浏览器检测。

谢谢。

Most implementations i've seen are for browser detection on the client side. I was just wondering if it was possible to do browser detection before sending any resources to the client.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

可是我不能没有你2024-11-17 13:14:42
var ua = request.headers['user-agent'],
    $ = {};

if (/mobile/i.test(ua))
    $.Mobile = true;

if (/like Mac OS X/.test(ua)) {
    $.iOS = /CPU( iPhone)? OS ([0-9\._]+) like Mac OS X/.exec(ua)[2].replace(/_/g, '.');
    $.iPhone = /iPhone/.test(ua);
    $.iPad = /iPad/.test(ua);
}

if (/Android/.test(ua))
    $.Android = /Android ([0-9\.]+)[\);]/.exec(ua)[1];

if (/webOS\//.test(ua))
    $.webOS = /webOS\/([0-9\.]+)[\);]/.exec(ua)[1];

if (/(Intel|PPC) Mac OS X/.test(ua))
    $.Mac = /(Intel|PPC) Mac OS X ?([0-9\._]*)[\)\;]/.exec(ua)[2].replace(/_/g, '.') || true;

if (/Windows NT/.test(ua))
    $.Windows = /Windows NT ([0-9\._]+)[\);]/.exec(ua)[1];

那应该对你有用。只需将其放入您的响应处理程序中即可。

var ua = request.headers['user-agent'],
    $ = {};

if (/mobile/i.test(ua))
    $.Mobile = true;

if (/like Mac OS X/.test(ua)) {
    $.iOS = /CPU( iPhone)? OS ([0-9\._]+) like Mac OS X/.exec(ua)[2].replace(/_/g, '.');
    $.iPhone = /iPhone/.test(ua);
    $.iPad = /iPad/.test(ua);
}

if (/Android/.test(ua))
    $.Android = /Android ([0-9\.]+)[\);]/.exec(ua)[1];

if (/webOS\//.test(ua))
    $.webOS = /webOS\/([0-9\.]+)[\);]/.exec(ua)[1];

if (/(Intel|PPC) Mac OS X/.test(ua))
    $.Mac = /(Intel|PPC) Mac OS X ?([0-9\._]*)[\)\;]/.exec(ua)[2].replace(/_/g, '.') || true;

if (/Windows NT/.test(ua))
    $.Windows = /Windows NT ([0-9\._]+)[\);]/.exec(ua)[1];

That should work for you. Just put it in your response handler.

日久见人心2024-11-17 13:14:42

Node 的 ua-parser 库(npm install ua-parser)公开了一组用于浏览器用户代理字符串的正则表达式。我强烈推荐它以满足您的需求。

The ua-parser library for node (npm install ua-parser) exposes a big set of regexes for browser user-agent strings. I'd strongly recommend it for your needs.

蘸点软妹酱2024-11-17 13:14:42

我使用 ua-parser-js 将其组合在一起。我确信它可以改进,但它很实用。

安装包:

sudo npm install ua-parser-js

在你的路由文件中需要 UAParser:

var UAParser = require('ua-parser-js');

用它做一些事情:

function ensureLatestBrowser(req, res, next) {
  var parser = new UAParser();
  var ua = req.headers['user-agent'];
  var browserName = parser.setUA(ua).getBrowser().name;
  var fullBrowserVersion = parser.setUA(ua).getBrowser().version;
  var browserVersion = fullBrowserVersion.split(".",1).toString();
  var browserVersionNumber = Number(browserVersion);

  if (browserName == 'IE' && browserVersion <= 9)
    res.redirect('/update/');
  else if (browserName == 'Firefox' && browserVersion <= 24)
    res.redirect('/update/');
  else if (browserName == 'Chrome' && browserVersion <= 29)
    res.redirect('/update/');
  else if (browserName == 'Canary' && browserVersion <= 32)
    res.redirect('/update/');
  else if (browserName == 'Safari' && browserVersion <= 5)
    res.redirect('/update/');
  else if (browserName == 'Opera' && browserVersion <= 16)
    res.redirect('/update/');
  else
    return next();
}

然后在你的路由中调用:

app.all(/^(?!(\/update)).*$/, ensureLatestBrowser);

如果你想看看你可以通过 UAParser 获得哪些其他信息,请查看他们的 演示页面。

I threw this together using ua-parser-js. I'm sure it can be improved but it's functional.

Install the package:

sudo npm install ua-parser-js

In your routes file require UAParser:

var UAParser = require('ua-parser-js');

Do some stuff with it:

function ensureLatestBrowser(req, res, next) {
  var parser = new UAParser();
  var ua = req.headers['user-agent'];
  var browserName = parser.setUA(ua).getBrowser().name;
  var fullBrowserVersion = parser.setUA(ua).getBrowser().version;
  var browserVersion = fullBrowserVersion.split(".",1).toString();
  var browserVersionNumber = Number(browserVersion);

  if (browserName == 'IE' && browserVersion <= 9)
    res.redirect('/update/');
  else if (browserName == 'Firefox' && browserVersion <= 24)
    res.redirect('/update/');
  else if (browserName == 'Chrome' && browserVersion <= 29)
    res.redirect('/update/');
  else if (browserName == 'Canary' && browserVersion <= 32)
    res.redirect('/update/');
  else if (browserName == 'Safari' && browserVersion <= 5)
    res.redirect('/update/');
  else if (browserName == 'Opera' && browserVersion <= 16)
    res.redirect('/update/');
  else
    return next();
}

and then in your route just call:

app.all(/^(?!(\/update)).*$/, ensureLatestBrowser);

If you want to see what other information you can get with UAParser check out their demo page.

梦与时光遇2024-11-17 13:14:42

我想对我的网站的移动版本进行简单的重定向,因此用户代理足够可靠。我想在服务器端执行此操作,这样我就不会浪费时间在客户端加载不必要的 css 和 js。 http://detectmobilebrowsers.com/ 具有最强大的正则表达式来匹配。因此,我整合了一些快速中间件,让您只需向应用程序添加两行代码即可完成重定向。

npm install detectormobilebrowsers 进行安装

express = require 'express'
mobile  = require 'detectmobilebrowsers'

app = express()
app.configure () ->
  app.use mobile.redirect 'http://m.domain.com'
app.get '/', (req, res) ->
  res.send 'Not on Mobile'
app.listen 3000

I wanted to do a simple redirection to a mobile version of my site, so user-agent is reliable enough. I wanted to do it server-side so I didn't waste time loading unnecessary css and js on the client. http://detectmobilebrowsers.com/ had the most robust regex to match. So I threw together some express middleware that will let you do the redirection by just adding two lines of code to your app.

npm install detectmobilebrowsers to install

express = require 'express'
mobile  = require 'detectmobilebrowsers'

app = express()
app.configure () ->
  app.use mobile.redirect 'http://m.domain.com'
app.get '/', (req, res) ->
  res.send 'Not on Mobile'
app.listen 3000
白昼2024-11-17 13:14:42

几个月前我发布了 device- detector-js

它是 Matomo device-Detector 的 TypeScript 端口,这是一个最初用 PHP 编写的强大的设备检测库。

它可以解析任何用户代理并检测浏览器、操作系统、使用的设备(台式机、平板电脑、手机、电视、汽车、控制台等)、品牌和型号。

安装

npm install device-detector-js

示例 - 简单的用户代理检测:

const DeviceDetector = require("device-detector-js");

const deviceDetector = new DeviceDetector();
const userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36";
const device = deviceDetector.parse(userAgent);

console.log(device);

查看 完整的 API 文档

I released device-detector-js a couple months ago.

It's a TypeScript port of Matomo device-detector, a powerful device detection library originally written in PHP.

It can parse any user agent and detect the browser, operating system, device used (desktop, tablet, mobile, tv, cars, console, etc.), brand and model.

Installation

npm install device-detector-js

Example - simple user agent detection:

const DeviceDetector = require("device-detector-js");

const deviceDetector = new DeviceDetector();
const userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81 Safari/537.36";
const device = deviceDetector.parse(userAgent);

console.log(device);

Take a look at the full API documentation.

人心善变2024-11-17 13:14:42
ua = request.headers['user-agent'];
if( /firefox/i.test(ua) )
  browser = 'firefox';
else if( /chrome/i.test(ua) )
  browser = 'chrome';
else if( /safari/i.test(ua) )
  browser = 'safari';
else if( /msie/i.test(ua) )
  browser = 'msie';
else
  browser = 'unknown';
ua = request.headers['user-agent'];
if( /firefox/i.test(ua) )
  browser = 'firefox';
else if( /chrome/i.test(ua) )
  browser = 'chrome';
else if( /safari/i.test(ua) )
  browser = 'safari';
else if( /msie/i.test(ua) )
  browser = 'msie';
else
  browser = 'unknown';
凹づ凸ル2024-11-17 13:14:42

大多数浏览器提供一个名为“User-Agent”的 HTTP 请求标头,这与客户端的 navigator.userAgent 属性相同。

Most browsers provide an HTTP request header called "User-Agent" This is the same as the navigator.userAgent property on the client side.

面犯桃花2024-11-17 13:14:42

如果您使用express,您可以轻松地检查 ua ,如下所示:

app.get('/ua', function(req, res){
    res.send('user ' + req.headers['user-agent']);
});

if your using express you can easily check the ua with something like this:

app.get('/ua', function(req, res){
    res.send('user ' + req.headers['user-agent']);
});
谁的新欢旧爱2024-11-17 13:14:42

我对 @duck5auce 的代码进行了一些改进,使其真正有用并支持 IE 10-12 (Edge)。

var getDevice = function(ua) {
    var $ = {active: false, subactive: false};

    if (/mobile/i.test(ua)) {
        $.active = 'mobile';
        $.Mobile = true;
    }

    if (/like Mac OS X/.test(ua)) {
        $.active = 'iOS';
        $.iOS = /CPU( iPhone)? OS ([0-9\._]+) like Mac OS X/.exec(ua)[2].replace(/_/g, '.');
        if (/like Mac OS X/.test(ua)) {
            $.subactive = 'iPhone';
            $.iPhone = /iPhone/.test(ua);
        }
        if (/like Mac OS X/.test(ua)) {
            $.subactive = 'iPad';
            $.iPad = /iPad/.test(ua);
        }
    }

    if (/Android/.test(ua)) {
        $.active = 'Android';
        $.Android = /Android ([0-9\.]+)[\);]/.exec(ua)[1];
    }

    if (/webOS\//.test(ua)) {
        $.active = 'webOS';
        $.webOS = /webOS\/([0-9\.]+)[\);]/.exec(ua)[1];
    }

    if (/(Intel|PPC) Mac OS X/.test(ua)) {
        $.active = 'Safari';
        $.Safari = /(Intel|PPC) Mac OS X ?([0-9\._]*)[\)\;]/.exec(ua)[2].replace(/_/g, '.') || true;
    }

    if (/Windows NT/.test(ua)) {
        $.active = 'IE';
        $.IE = /Windows NT ([0-9\._]+)[\);]/.exec(ua)[1];
    }
    if (/MSIE/.test(ua)) {
        $.active = 'IE';
        $.IE = /MSIE ([0-9]+[\.0-9]*)/.exec(ua)[1];
    }
    if (/Trident/.test(ua)) {
        $.active = 'IE';
        $.IE = /Trident\/.*rv:([0-9]+[\.0-9]*)/.exec(ua)[1];
    }
    if (/Edge\/\d+/.test(ua)) {
        $.active = 'IE Edge';
        $.IE = /Edge\/(\d+)/.exec(ua)[1];
    }

    return $.active + ' ' + $[$.active] + ($.subactive && ' ' + $.subactive + ' ' + $[$.subactive]);
};

I improved a bit @duck5auce's code to be actually useful and support IE 10-12 (Edge).

var getDevice = function(ua) {
    var $ = {active: false, subactive: false};

    if (/mobile/i.test(ua)) {
        $.active = 'mobile';
        $.Mobile = true;
    }

    if (/like Mac OS X/.test(ua)) {
        $.active = 'iOS';
        $.iOS = /CPU( iPhone)? OS ([0-9\._]+) like Mac OS X/.exec(ua)[2].replace(/_/g, '.');
        if (/like Mac OS X/.test(ua)) {
            $.subactive = 'iPhone';
            $.iPhone = /iPhone/.test(ua);
        }
        if (/like Mac OS X/.test(ua)) {
            $.subactive = 'iPad';
            $.iPad = /iPad/.test(ua);
        }
    }

    if (/Android/.test(ua)) {
        $.active = 'Android';
        $.Android = /Android ([0-9\.]+)[\);]/.exec(ua)[1];
    }

    if (/webOS\//.test(ua)) {
        $.active = 'webOS';
        $.webOS = /webOS\/([0-9\.]+)[\);]/.exec(ua)[1];
    }

    if (/(Intel|PPC) Mac OS X/.test(ua)) {
        $.active = 'Safari';
        $.Safari = /(Intel|PPC) Mac OS X ?([0-9\._]*)[\)\;]/.exec(ua)[2].replace(/_/g, '.') || true;
    }

    if (/Windows NT/.test(ua)) {
        $.active = 'IE';
        $.IE = /Windows NT ([0-9\._]+)[\);]/.exec(ua)[1];
    }
    if (/MSIE/.test(ua)) {
        $.active = 'IE';
        $.IE = /MSIE ([0-9]+[\.0-9]*)/.exec(ua)[1];
    }
    if (/Trident/.test(ua)) {
        $.active = 'IE';
        $.IE = /Trident\/.*rv:([0-9]+[\.0-9]*)/.exec(ua)[1];
    }
    if (/Edge\/\d+/.test(ua)) {
        $.active = 'IE Edge';
        $.IE = /Edge\/(\d+)/.exec(ua)[1];
    }

    return $.active + ' ' + $[$.active] + ($.subactive && ' ' + $.subactive + ' ' + $[$.subactive]);
};
匿名。2024-11-17 13:14:42

强大的 npm useragent
Useragent 允许您使用手动调整的专用正则表达式进行浏览器匹配,以高精度解析用户代理字符串。需要该数据库来确保每个浏览器都被正确解析,因为每个浏览器供应商都实现了自己的用户代理架构。这就是为什么常规用户代理解析器存在重大问题,因为它们很可能解析出错误的浏览器名称或将渲染引擎版本与浏览器的实际版本混淆。

Powerfull npm useragent.
Useragent allows you to parse user agent string with high accuracy by using hand tuned dedicated regular expressions for browser matching. This database is needed to ensure that every browser is correctly parsed as every browser vendor implements it's own user agent schema. This is why regular user agent parsers have major issues because they will most likely parse out the wrong browser name or confuse the render engine version with the actual version of the browser.

北座城市2024-11-17 13:14:42

我有类似的要求,并且遇到了这个名为 detect-browser 的节点包。

const { detect } = require('detect-browser');
const browser = detect();

if (browser) {
  console.log(browser.name);
  console.log(browser.version);
  console.log(browser.os);
}

或者,如果您想根据特定浏览器执行任何操作,您也可以使用如下所示的 switch case

const { detect } = require('detect-browser');
const browser = detect();

// handle the case where we don't detect the browser
switch (browser && browser.name) {
  case 'chrome':
  case 'firefox':
    console.log('supported');
    break;

  case 'edge':
    console.log('kinda ok');
    break;

  default:
    console.log('not supported');
}

I had a similar requirement and I came across this node package called detect-browser.

const { detect } = require('detect-browser');
const browser = detect();

if (browser) {
  console.log(browser.name);
  console.log(browser.version);
  console.log(browser.os);
}

Or if you wanted to perform any action depending on a specific browser you could also use a switch case like below

const { detect } = require('detect-browser');
const browser = detect();

// handle the case where we don't detect the browser
switch (browser && browser.name) {
  case 'chrome':
  case 'firefox':
    console.log('supported');
    break;

  case 'edge':
    console.log('kinda ok');
    break;

  default:
    console.log('not supported');
}
涫野音2024-11-17 13:14:42

如果你想在模板层控制移动设备,我只是为此编写了一个模块。
https://github.com/Fresheyeball/isMobile-node

If you want to control mobile in the templating layer, I just wrote a module for that.
https://github.com/Fresheyeball/isMobile-node

め七分饶幸2024-11-17 13:14:42

您可能想查看 Apache DeviceMap

现在,开箱即用的 JavaScript 库更多地在客户端,但很多都将以类似的方式在 Node.JS 或 Angular 上工作。与 UA 字符串的简单模式匹配不同,DeviceMap 在其基于 W3C 标准的设备描述存储库 (DDR) 中提供了大量设备和设备系列。

You might want to have a look at Apache DeviceMap.

JavaScript libraries out of the box are more on the client side right now, but much will work on Node.JS or Angular in a similar way. Unlike simple pattern matching of UA strings DeviceMap comes with a vast range of devices and device families in its Device Description Repository (DDR) based on W3C standards.

寒冷纷飞旳雪2024-11-17 13:14:42

[这是另一种变体或同化供您考虑。]

它更加通用且进一步简化。

您可以传递请求或任何具有“headers”属性的对象或其可以是 headers 属性,您可以选择任何标签来搜索对象或标题或实际用户代理字符串本身的参数。

它使用了之前发布的移动和表格检查正则表达式,并简单地返回该结果,但通过首先验证输入,可以插入各种东西。

您甚至可以覆盖默认的正则表达式(可选)作为参数传递。 {我将把进一步的扩展留给有灵感的人。}
如果在范围内等,还可以有另一种方式默认从请求全局存储的用户代理。

mobTabCheck: function( ua, lbl, rgx ) {  /* mobile tablet check; UserAgent or request, or any object with optional search label  */
    if( ua === und ) return false;
    if( ua !== und && ua.constructor !== String ) {
        if( lbl === und ) lbl = 'user-agent';
        if( ua.headers !== und ) ua = ua.headers[ lbl ];
        else ua = ua[ lbl ];
    }
    if( rgx === und ) rgx = /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/;
    if( rgx.constructor === String ) rgx = new RegExp( rgx );
    return rgx.test( ua );
}

这个正则表达式来自这里......
https://gist.github.com/dalethedeveloper/1503252/931cc8b613aaa930ef92a4027916 e6687d07feac

98%解决方案。我不知道它是否像我的函数标题所暗示的那样检查平板电脑。

这个函数的标题(和一些参数)真的应该重命名吗?... serachObjectForLabelThatMatchesThisRegex

除了所有默认值使它成为一个单一参数目的的东西。

另外,我将函数集保留为键的值,您可以按照自己喜欢的方式存储它......如果您使用它,请向我保证没有 var 或 const 。

let mobTabCheck = function() {};

[Here is another variation or assimilation for your consideration.]

It is more versatile and simplified further.

You can pass the Request or any object with a 'headers' property or it could be the headers property and you can pick any label to search for the parameter on the object or the headers or the actual user agent string itself.

It used the previously posted Mobile and Table Checking Regex, and simply returns that result, but by first sanctifying the input, one can plug various things in.

You can even override the default regex optionally passable as an argument. {I'll leave that further extension to the inspired.}
Also one could have another way to default to the globally stored user-agent from the request if in scope etc.

mobTabCheck: function( ua, lbl, rgx ) {  /* mobile tablet check; UserAgent or request, or any object with optional search label  */
    if( ua === und ) return false;
    if( ua !== und && ua.constructor !== String ) {
        if( lbl === und ) lbl = 'user-agent';
        if( ua.headers !== und ) ua = ua.headers[ lbl ];
        else ua = ua[ lbl ];
    }
    if( rgx === und ) rgx = /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/;
    if( rgx.constructor === String ) rgx = new RegExp( rgx );
    return rgx.test( ua );
}

This Regex came from here...
https://gist.github.com/dalethedeveloper/1503252/931cc8b613aaa930ef92a4027916e6687d07feac

The 98% Solution. I don't know if it checks tablets like my function title implies.

Really the title of this function (and some arguments) should be rename maybe?... serachObjectForLabelThatMatchesThisRegex

except all the defaults make it a single argument purposed thing.

Also I leave the function set as a key's value, which you can store however you prefer like... just promise me no var or const if you use it.

let mobTabCheck = function() {};
剧终人散尽2024-11-17 13:14:42

用于设备、浏览器、操作系统的服务器检测。我推荐 https://www.npmjs.com/package/node-device-detector< /a>

支持客户端提示。

for server detection of the device, browser, os. I recommend https://www.npmjs.com/package/node-device-detector

there is support for clienthints.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文