Fra*_*nkC 738 javascript browser-detection
我有FF,Chrome,IE,Opera和Safari的5个插件/扩展.
如何识别用户浏览器并重定向(单击安装按钮后)以下载相应的插件?
Rob*_*b W 1560
用于浏览器可靠检测的Google搜索通常会导致检查用户代理字符串.这种方法不可靠,因为欺骗这个值是微不足道的.
我编写了一种通过duck-typing来检测浏览器的方法.
如果确实有必要,请仅使用浏览器检测方法,例如显示特定于浏览器的指令以安装扩展程序.尽可能使用特征检测.
演示:https://jsfiddle.net/311aLtkz/
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 71
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;
Run Code Online (Sandbox Code Playgroud)
在先前的方法依赖于渲染引擎(的性质-moz-box-sizing
和-webkit-transform
)来检测浏览器.这些前缀最终将被删除,因此为了使检测更加健壮,我切换到特定于浏览器的特性:
document.documentMode
.StyleMedia
构造函数.不包括Trident让我们离开Edge.InstallTrigger
chrome
对象,包含多个属性,包括已记录的chrome.webstore
对象.
chrome.webstore
在最新版本中,不推荐使用Update 3 并且未定义更新SafariRemoteNotification
,这是在7.1版之后引入的,以涵盖3.0及以上版本的所有Safaris.window.opera
已存在多年,但当Opera用Blink + V8(Chromium使用)取代其引擎时,它将被删除.
chrome
定义了对象(但chrome.webstore
不是).由于Opera努力克隆Chrome,我使用用户代理嗅探来实现此目的.!!window.opr && opr.addons
可用于检测Opera 20+(常青树).CSS.supports()
在Blink中推出.当然,与Opera中使用的Blink相同.2016年11月更新,包括检测9.1.3及更高版本的Safari浏览器
在2018年8月更新,以更新有关chrome,firefox IE和edge的最新成功测试.
在2019年1月更新以修复Chrome检测(因为window.chrome.webstore折旧)并包含最新的成功测试.
Nim*_*esh 121
您可以尝试以下方式检查浏览器版本.
<!DOCTYPE html>
<html>
<body>
<p>What is the name(s) of your browser?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 )
{
alert('Opera');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
alert('Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
alert('Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
alert('IE');
}
else
{
alert('unknown');
}
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果您只需要知道IE浏览器版本,那么您可以按照以下代码.此代码适用于IE6到IE11的版本
<!DOCTYPE html>
<html>
<body>
<p>Click on Try button to check IE Browser version.</p>
<button onclick="getInternetExplorerVersion()">Try it</button>
<p id="demo"></p>
<script>
function getInternetExplorerVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var rv = -1;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
//For IE 11 >
if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
alert(rv);
}
}
else {
alert('otherbrowser');
}
}
else {
//For < IE11
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
return false;
}}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Raf*_*yng 59
我知道使用lib可能有点过分,但只是为了丰富线程,你可以检查is.js这样做的方式:
is.firefox();
is.ie(6);
is.not.safari();
Run Code Online (Sandbox Code Playgroud)
wil*_*ire 43
如果有人发现这个有用,我已经将Rob W的答案变成了一个返回浏览器字符串而不是浮动多个变量的函数.由于浏览器在没有重新加载的情况下也无法真正改变,我已经使其缓存结果以防止它在下次调用函数时需要将其解决.
/**
* Gets the browser name or returns an empty string if unknown.
* This function also caches the result to provide for any
* future calls this function has.
*
* @returns {string}
*/
var browser = function() {
// Return cached result if avalible, else get result then cache it.
if (browser.prototype._cachedResult)
return browser.prototype._cachedResult;
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
return browser.prototype._cachedResult =
isOpera ? 'Opera' :
isFirefox ? 'Firefox' :
isSafari ? 'Safari' :
isChrome ? 'Chrome' :
isIE ? 'IE' :
isEdge ? 'Edge' :
isBlink ? 'Blink' :
"Don't know";
};
console.log(browser());
Run Code Online (Sandbox Code Playgroud)
Kyl*_*Mit 36
以下是几个处理浏览器检测的着名库,截至2019年2月.
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
" v" + result.parsedResult.browser.version +
" on " + result.parsedResult.os.name);
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/bowser@2.4.0/es5.js"></script>
Run Code Online (Sandbox Code Playgroud)
console.log(platform);
document.write("You are using " + platform.name +
" v" + platform.version +
" on " + platform.os);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
console.log($.browser)
document.write("You are using " + $.browser.name +
" v" + $.browser.versionNumber +
" on " + $.browser.platform);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
" v" + result.browser.version +
" on " + result.os.family);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
" v" + BrowserDetect.version +
" on " + BrowserDetect.OS);
Run Code Online (Sandbox Code Playgroud)
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Run Code Online (Sandbox Code Playgroud)
Ale*_*lin 14
简短的变种
var browser = (function(){
var test = function(regexp) { return regexp.test(window.navigator.userAgent);}
switch(true){
case test(/edge/i): return "edge";
case test(/opr/i) && (!!window.opr || !!window.opera): return "opera";
case test(/chrome/i) && !!window.chrome: return "chrome";
case test(/trident/i) : return "ie";
case test(/firefox/i) : return "firefox";
case test(/safari/i): return "safari";
default: return "other";
}
})();
console.log(browser)
Run Code Online (Sandbox Code Playgroud)
pil*_*lau 11
这是Rob的答案的2016年调整版,包括Microsoft Edge和Blink的检测:
(编辑:我用上述信息更新了Rob的答案.)
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;
/* Results: */
console.log("isOpera", isOpera);
console.log("isFirefox", isFirefox);
console.log("isSafari", isSafari);
console.log("isIE", isIE);
console.log("isEdge", isEdge);
console.log("isChrome", isChrome);
console.log("isBlink", isBlink);
Run Code Online (Sandbox Code Playgroud)
这种方法的优点在于它依赖于浏览器引擎属性,因此它甚至涵盖了衍生浏览器,例如Yandex或Vivaldi,它们实际上与他们使用的引擎的主要浏览器兼容.唯一的例外是Opera,它依赖于用户代理嗅探,但今天(即版本15及以上)甚至Opera本身只是Blink的一个shell.
谢谢大家.我在最近的浏览器上测试了代码片段:Chrome 55,Firefox 50,IE 11和Edge 38,我想出了以下组合,这些组合对我来说都适用.我确信它可以改进,但它是一个快速的解决方案,无论谁需要:
var browser_name = '';
isIE = /*@cc_on!@*/false || !!document.documentMode;
isEdge = !isIE && !!window.StyleMedia;
if(navigator.userAgent.indexOf("Chrome") != -1 && !isEdge)
{
browser_name = 'chrome';
}
else if(navigator.userAgent.indexOf("Safari") != -1 && !isEdge)
{
browser_name = 'safari';
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
browser_name = 'firefox';
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
browser_name = 'ie';
}
else if(isEdge)
{
browser_name = 'edge';
}
else
{
browser_name = 'other-browser';
}
$('html').addClass(browser_name);
Run Code Online (Sandbox Code Playgroud)
它为HTML添加了一个CSS类,其中包含浏览器的名称.
不知道它是否对任何人有用,但是这里有一个使TypeScript满意的变体。
export function getBrowser() {
// Opera 8.0+
if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
return 'opera';
}
// Firefox 1.0+
if (typeof window["InstallTrigger"] !== 'undefined') {
return 'firefox';
}
// Safari 3.0+ "[object HTMLElementConstructor]"
if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
return 'safari';
}
// Internet Explorer 6-11
if (/*@cc_on!@*/false || !!document["documentMode"]) {
return 'ie';
}
// Edge 20+
if (!(/*@cc_on!@*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
return 'edge';
}
// Chrome 1+
if (!!window["chrome"] && !!window["chrome"].webstore) {
return 'chrome';
}
// Blink engine detection
if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
return 'blink';
}
Run Code Online (Sandbox Code Playgroud)
}
您可以使用try
和catch
使用不同的浏览器错误消息.IE和边缘混在一起,但我使用了Rob W的鸭子打字(基于这个项目:https://www.khanacademy.org/computer-programming/i-have-opera/2395080328).
var getBrowser = function() {
try {
var e;
var f = e.width;
} catch(e) {
var err = e.toString();
if(err.indexOf("not an object") !== -1) {
return "safari";
} else if(err.indexOf("Cannot read") !== -1) {
return "chrome";
} else if(err.indexOf("e is undefined") !== -1) {
return "firefox";
} else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
if(!(false || !!document.documentMode) && !!window.StyleMedia) {
return "edge";
} else {
return "IE";
}
} else if(err.indexOf("cannot convert e into object") !== -1) {
return "opera";
} else {
return undefined;
}
}
};
Run Code Online (Sandbox Code Playgroud)
UAParser是 JavaScript 库之一,用于从 userAgent 字符串中识别浏览器、引擎、操作系统、CPU 和设备类型/型号。
有可用的 CDN。在这里,我提供了一个使用 UAParser 检测浏览器的示例代码。
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js@0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
var parser = new UAParser();
var result = parser.getResult();
console.log(result.browser); // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在您可以使用 的值result.browser
来有条件地对您的页面进行编程。
源码教程:如何使用JavaScript检测浏览器、引擎、操作系统、CPU和设备?
检测桌面和移动浏览器:Edge、Opera、Chrome、Safari、Firefox、IE
我对 @nimesh 代码做了一些更改,现在它也适用于 Edge,并且修复了 Opera 问题:
function getBrowserName() {
if ( navigator.userAgent.indexOf("Edge") > -1 && navigator.appVersion.indexOf('Edge') > -1 ) {
return 'Edge';
}
else if( navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 )
{
return 'Opera';
}
else if( navigator.userAgent.indexOf("Chrome") != -1 )
{
return 'Chrome';
}
else if( navigator.userAgent.indexOf("Safari") != -1)
{
return 'Safari';
}
else if( navigator.userAgent.indexOf("Firefox") != -1 )
{
return 'Firefox';
}
else if( ( navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ) ) //IF IE > 10
{
return 'IE';
}
else
{
return 'unknown';
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢@nimesh 用户:2063564
如果您需要知道某个特定浏览器的数字版本是什么,您可以使用以下代码段。目前它会告诉你 Chrome/Chromium/Firefox 的版本:
var match = $window.navigator.userAgent.match(/(?:Chrom(?:e|ium)|Firefox)\/([0-9]+)\./);
var ver = match ? parseInt(match[1], 10) : 0;
Run Code Online (Sandbox Code Playgroud)
检测浏览器及其版本
此代码片段基于MDN的文章。他们给出了有关可用于检测浏览器名称的各种关键字的简短提示。
上图中显示的数据不足以检测所有浏览器,例如Firefox 的 userAgent 将使用 Fxios 作为关键字,而不是 Firefox。
还进行了一些更改以检测Edge和UCBrowser等浏览器
目前,通过在开发工具的帮助下更改 userAgent(如何更改 userAgent),代码已针对以下浏览器进行了测试:
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
Run Code Online (Sandbox Code Playgroud)
小智 5
还有一种不那么“hacky”的方法适用于所有流行的浏览器。Google 在他们的Closure Library 中包含了浏览器检查。特别是,看看goog.userAgent
和goog.userAgent.product
。通过这种方式,如果浏览器呈现的方式发生变化,您也可以及时了解最新信息(假设您始终运行最新版本的闭包编译器。)
您可以使用 Detect-browser.js,JavaScript 库,检测并打印浏览器信息对象,包括浏览器语言/名称、用户代理、设备类型、用户操作系统、引荐来源网址、在线/0离线、用户时区、屏幕分辨率和启用的 cookie 。
从这里获取detector-browser.js
它会给你类似的东西:
这是我的定制解决方案。
const inBrowser = typeof window !== 'undefined'
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE =
UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
const isEdge = UA && /edg/i.test(UA)
const isAndroid = UA && UA.indexOf('android') > 0
const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
const isChrome =
UA &&
/chrome|crios/i.test(UA) &&
!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
const isGoogleBot = UA && /googlebot/i.test(UA)
const isChromium = UA && /chromium/i.test(UA)
const isUcBrowser = UA && /ucbrowser/i.test(UA)
const isSafari =
UA &&
/safari/i.test(UA) &&
!/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
const isOpera = UA && /opr|opera/i.test(UA)
const isMobile =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
const isSamsung = UA && /samsungbrowser/i.test(UA)
const isIPad = UA && /ipad/.test(UA)
const isIPhone = UA && /iphone/.test(UA)
const isIPod = UA && /ipod/.test(UA)
console.log({
UA,
isAndroid,
isChrome,
isChromium,
isEdge,
isFirefox,
isGoogleBot,
isIE,
isMobile,
isIOS,
isIPad,
isIPhone,
isIPod,
isOpera,
isSafari,
isSamsung,
isUcBrowser,
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
782127 次 |
最近记录: |