서버 측 브라우저 감지? node.js
내가 본 대부분의 구현은 클라이언트 측에서 브라우저 감지를위한 것입니다. 클라이언트에 리소스를 보내기 전에 브라우저 감지를 수행 할 수 있는지 궁금합니다.
감사.
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];
그것은 당신을 위해 일할 것입니다. 응답 핸들러에 넣으십시오.
UA-파서 노드 라이브러리 ( npm install ua-parser
) 브라우저 사용자 에이전트 문자열에 대한 정규 표현식에의 큰 세트를 제공합니다. 귀하의 필요에 따라 강력히 권장합니다.
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로 얻을 수있는 다른 정보를 보려면 데모 페이지를 확인 하십시오.
내 사이트의 모바일 버전으로 간단한 리디렉션을 수행하고 싶었으므로 user-agent가 충분히 신뢰할 수 있습니다. 서버 측에서하고 싶었 기 때문에 클라이언트에서 불필요한 CSS와 js를로드하는 데 시간을 낭비하지 않았습니다. http://detectmobilebrowsers.com/ 에는 가장 강력한 정규식이 일치했습니다. 그래서 저는 앱에 두 줄의 코드를 추가하여 리디렉션을 수행 할 수있는 몇 가지 익스프레스 미들웨어를 모았습니다.
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
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';
Express를 사용하는 경우 다음과 같이 쉽게 ua를 확인할 수 있습니다.
app.get('/ua', function(req, res){
res.send('user ' + req.headers['user-agent']);
});
대부분의 브라우저는 "User-Agent"라는 HTTP 요청 헤더를 제공합니다. 이는 클라이언트 측의 navigator.userAgent 속성과 동일합니다.
이 코드 http://detectmobilebrowser.com/ 시도
여기 또 하나가 있습니다 : https://github.com/koudelka/node-useragent_parser
저는 최근 몇 달 전에 device-detector-js를 출시했습니다 .
원래 PHP로 작성된 강력한 장치 탐지 라이브러리 인 Matomo 장치 탐지기의 TypeScript 포트입니다.
모든 사용자 에이전트를 구문 분석하고 브라우저, 운영 체제, 사용 된 장치 (데스크톱, 태블릿, 모바일, TV, 자동차, 콘솔 등), 브랜드 및 모델을 감지 할 수 있습니다.
엄중 한 테스트를 거쳤으며 6000 개 이상의 테스트에 의존하여 수천 개의 다른 장치를 감지합니다.
설치
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 문서를 살펴보십시오 .
템플릿 레이어에서 모바일을 제어하려면 모듈을 작성했습니다. https://github.com/Fresheyeball/isMobile-node
실제로 유용하고 IE 10-12 (Edge)를 지원하도록 @ duck5auce의 코드를 약간 개선했습니다.
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]);
};
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.
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.
[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() {};
참고URL : https://stackoverflow.com/questions/6163350/server-side-browser-detection-node-js
'IT TIP' 카테고리의 다른 글
기본 생성자없이 객체 배열 초기화 (0) | 2020.12.10 |
---|---|
JSF 2.0에서 세션을 무효화하는 방법은 무엇입니까? (0) | 2020.12.10 |
Ruby-첫 번째 하위 문자열을 다른 문자열로 교체 (0) | 2020.12.10 |
Java-값으로 문자열 배열을 어떻게 만듭니 까? (0) | 2020.12.10 |
둘 이상의 디테일 뷰 컨트롤러를 푸시 할 때 "DetailViewController의 모양 전환을 시작 / 종료하기위한 불균형 호출" (0) | 2020.12.10 |