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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6163350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:30:38  来源:igfitidea点击:

server-side browser detection? node.js

javascriptbrowsernode.jsbrowser-detection

提问by fancy

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.

谢谢。

回答by McKayla

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.

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

回答by S M

The ua-parserlibrary 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.

节点 ( )的ua-parsernpm install ua-parser公开了大量用于浏览器用户代理字符串的正则表达式。我强烈推荐它来满足您的需求。

回答by Donald Gary

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

我使用ua-parser-js把它放在一起。我相信它可以改进,但它的功能。

Install the package:

安装软件包:

sudo npm install ua-parser-js

In your routes file require UAParser:

在你的路由文件中需要 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.

如果您想查看使用 UAParser 可以获得的其他信息,请查看他们的演示页面。

回答by Overflow289

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.

我想做一个简单的重定向到我网站的移动版本,所以用户代理足够可靠。我想在服务器端做,所以我没有浪费时间在客户端加载不必要的 css 和 js。 http://detectmobilebrowsers.com/拥有最强大的正则表达式来匹配。因此,我将一些快速中间件放在一起,让您只需向应用程序添加两行代码即可进行重定向。

npm install detectmobilebrowsersto install

npm install detectmobilebrowsers安装

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

回答by Nino Paolo

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';

回答by Etienne Martin

I released device-detector-jsa couple months ago.

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

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

它是 Matomo device-detector 的 TypeScript 端口,这是一个最初用 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.

查看完整的 API 文档

回答by bhurlow

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

如果您使用 express,您可以使用以下内容轻松检查 ua:

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

回答by tomislav

回答by Maz

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

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