Javascript 如何检测chrome和safari浏览器(webkit)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12625876/
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 10:53:22  来源:igfitidea点击:

How to detect chrome and safari browser (webkit)

javascriptjquery

提问by Rouge

I am trying to detect the chrome and safari browser using jquery or javascript. I thought we are not supposed to use jQuery.browser. Are there any suggestions here? Thanks a lot!

我正在尝试使用 jquery 或 javascript 检测 chrome 和 safari 浏览器。我认为我们不应该使用 jQuery.browser。这里有什么建议吗?非常感谢!

回答by Oscar Jara

If you dont want to use $.browser, take a look at case 1, otherwise maybe case 2and 3can help you just to get informedbecause it is not recommended to use $.browser(the user agent can be spoofed using this). An alternative can be using jQuery.supportthat will detect feature support and not agent info.

如果您不想使用$.browser,请查看案例 1,否则也许案例 23可以帮助您了解情况,因为不建议使用它$.browser(用户代理可能会被欺骗使用)。可以使用另一种方法来jQuery.support检测功能支持而不是代理信息。

But...

但...

If you insist on getting browser type (just Chrome or Safari)but not using $.browser, case 1is what you looking for...

如果您坚持获取浏览器类型(仅 Chrome 或 Safari)但不使用$.browser,则案例 1就是您要查找的...



This fits your requirement:

这符合您的要求:

Case 1:(No jQuery and no $.browser, just javascript)

案例 1:(没有 jQuery 和 $.browser,只有 javascript)

Live Demo:http://jsfiddle.net/oscarj24/DJ349/

现场演示:http : //jsfiddle.net/oscarj24/DJ349/

var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);

if (isChrome) alert("You are using Chrome!");
if (isSafari) alert("You are using Safari!");


These cases I used in times before and worked well but they are not recommended...

我以前使用过这些案例并且效果很好,但不推荐它们......

Case 2:(Using jQuery and $.browser, this one is tricky)

案例2:(使用jQuery和$.browser,这个有点棘手)

Live Demo:http://jsfiddle.net/oscarj24/gNENk/

现场演示:http : //jsfiddle.net/oscarj24/gNENk/

$(document).ready(function(){

    /* Get browser */
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

    /* Detect Chrome */
    if($.browser.chrome){
        /* Do something for Chrome at this point */
        /* Finally, if it is Chrome then jQuery thinks it's 
           Safari so we have to tell it isn't */
        $.browser.safari = false;
    }

    /* Detect Safari */
    if($.browser.safari){
        /* Do something for Safari */
    }

});

Case 3:(Using jQuery and $.browser, "elegant" solution)

案例3:(使用jQuery和$.browser,“优雅”的解决方案)

Live Demo:http://jsfiddle.net/oscarj24/uJuEU/

现场演示:http : //jsfiddle.net/oscarj24/uJuEU/

$.browser.chrome = $.browser.webkit && !!window.chrome;
$.browser.safari = $.browser.webkit && !window.chrome;

if ($.browser.chrome) alert("You are using Chrome!");
if ($.browser.safari) alert("You are using Safari!");

回答by vsync

Most of the answers here are obsolete, there is no more jQuery.browser, and why would anyone even use jQuery or would sniff the User Agentis beyond me.

这里的大多数答案都已经过时了,没有更多了jQuery.browser,为什么有人甚至会使用 jQuery 或者会嗅到User Agent超出我的范围。

Instead of detecting a browser, you should rather detect a feature(whether it's supported or not).
The following is falsein Mozilla Firefox, Microsoft Edge; it is truein Google Chrome.

与其检测浏览器,不如检测一个功能(无论是否支持)。
以下是false在 Mozilla Firefox、Microsoft Edge 中;它true在谷歌浏览器中。

"webkitLineBreak" in document.documentElement.style

Note this is not future-proof.A browser could implement the -webkit-line-breakproperty at any time in the future, thus resulting in false detection. Then you can just look at the document object in Chrome and pick anything with webkitprefix and check for that to be missing in other browsers.

请注意,这不是面向未来的。浏览器可以-webkit-line-break在未来的任何时间实现该属性,从而导致错误检测。然后你可以在 Chrome 中查看文档对象并选择带有webkit前缀的任何内容并检查它是否在其他浏览器中丢失。

回答by Konstantin Dinev

Instead of detecting a browser, you should rather detect a feature (whether it's supported or not). This is what Modernizrdoes.

与其检测浏览器,不如检测一个功能(无论是否支持)。这就是Modernizr所做的。

Of course there are cases where you still need to check the browser because you need to work around an issue and not to detect a feature. Specific WebKitcheck which does not use jQuery $.browser:

当然,在某些情况下,您仍然需要检查浏览器,因为您需要解决问题而不是检测功能。WebKit不使用 jQuery 的特定检查$.browser

var isWebKit = !!window.webkitURL;

As some of the comments suggested the above approach doesn't work for older Safari versions. Updating with another approach suggested in comments and by another answer:

由于一些评论表明上述方法不适用于较旧的 Safari 版本。使用评论和另一个答案中建议的另一种方法进行更新:

var isWebKit = 'WebkitAppearance' in document.documentElement.style;

回答by NVRM

There is still quirks and inconsistencies in 2019.

2019年仍然存在怪癖和不一致之处。

For example with scaled svg and pointer events, between browsers.

例如,在浏览器之间缩放 svg 和指针事件。

None of the answer of this topic are working anymore. (maybe those with jquery)

这个话题的答案都不再起作用了。(也许那些有jquery 的

Here is an alternative, by testing with javascript if a css rule is supported, via the native CSS support api. Might evolve, to be adapted!

这是一种替代方法,通过原生CSS 支持 api使用 javascript 测试是否支持 css 规则。可能会进化,要适应!

Note that it's possible to pass many css rules separated by a semicolon, for the finest detection.

请注意,可以传递许多由分号分隔的 css 规则,以实现最佳检测。

if (CSS.supports("( -webkit-box-reflect:unset )")){
  console.log("WEBKIT BROWSER")
  // More math...
 } else {
  console.log("ENJOY")
 }

if (CSS.supports("( -moz-user-select:unset )")){
  console.log("FIREFOX!!!")
 }

Beware to not use it in loops, for performance it's better to populate a constant on load:

注意不要在循环中使用它,为了提高性能,最好在加载时填充常量:

const ff = CSS.supports("( -moz-user-select:unset )")
if (ff){ //... } 

Using CSS only, the above would be:

使用CSS,以上将是:

@supports (-webkit-box-reflect:unset) {
  div {
    background: red
  }
}

@supports (-moz-user-select:unset) {
  div {
    background: green
  }
}
<div>
  Hello world!!
</div>

List of possible -webkit- only css rules.

可能的 -webkit-only css 规则列表。

List of possible -moz- only rules.

可能的 -moz-only 规则列表。

Can I use css support?

我可以使用 css 支持吗?

回答by 19h

/WebKit/.test(navigator.userAgent)— that's it.

/WebKit/.test(navigator.userAgent)- 就是这样。

回答by Quentin

I am trying to detect the chrome and safari browser using jquery or javascript.

我正在尝试使用 jquery 或 javascript 检测 chrome 和 safari 浏览器。

Use jQuery.browser

jQuery.browser

I thought we are not supposed to use jQuery.browser.

我认为我们不应该使用 jQuery.browser。

That's because detecting browsers is a bad idea. It is still the best way to detect the browser (when jQuery is involved) if you really intend to do that.

那是因为检测浏览器是一个坏主意。如果您真的打算这样做,它仍然是检测浏览器的最佳方法(当涉及 jQuery 时)。

回答by Hasan Al-Natour

you can use this minified jQuery snippet to detect if your user is viewing using a mobile device. If you need to test for a specific device I've included a collection of JavaScript snippets below which can be used to detect various mobile handheld devices such as iPad, iPhone, iPod, iDevice, Andriod, Blackberry, WebOs and Windows Phone.

您可以使用这个缩小的 jQuery 片段来检测您的用户是否正在使用移动设备查看。如果您需要测试特定设备,我在下面提供了一组 JavaScript 片段,可用于检测各种移动手持设备,例如 iPad、iPhone、iPod、iDevice、Andriod、Blackberry、WebOs 和 Windows Phone。

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 * jQuery.browser.mobile will be true if the browser is a mobile device
 **/

    (function(a){jQuery.browser.mobile=/android.+mobile|avantgo|bada/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)/|plucker|pocket|psp|symbian|treo|up.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw-(n|u)|c55/|capi|ccwa|cdm-|cell|chtm|cldc|cmd-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc-s|devi|dica|dmob|do(c|p)o|ds(12|-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(-|_)|g1 u|g560|gene|gf-5|g-mo|go(.w|od)|gr(ad|un)|haie|hcit|hd-(m|p|t)|hei-|hi(pt|ta)|hp( i|ip)|hs-c|ht(c(-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i-(20|go|ma)|i230|iac( |-|/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |/)|klon|kpt |kwc-|kyo(c|k)|le(no|xi)|lg( g|/(k|l|u)|50|54|e-|e/|-[a-w])|libw|lynx|m1-w|m3ga|m50/|ma(te|ui|xo)|mc(01|21|ca)|m-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|-([1-8]|c))|phil|pire|pl(ay|uc)|pn-2|po(ck|rt|se)|prox|psio|pt-g|qa-a|qc(07|12|21|32|60|-[2-7]|i-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55/|sa(ge|ma|mm|ms|ny|va)|sc(01|h-|oo|p-)|sdk/|se(c(-|0|1)|47|mc|nd|ri)|sgh-|shar|sie(-|m)|sk-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h-|v-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl-|tdg-|tel(i|m)|tim-|t-mo|to(pl|sh)|ts(70|m-|m3|m5)|tx-9|up(.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(-|2|g)|yas-|your|zeto|zte-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

Example Usage:

示例用法:

if(jQuery.browser.mobile)
{
console.log(‘You are using a mobile device!');
}
else
{
console.log(‘You are not using a mobile device!');
}

Detect iPad

检测 iPad

var isiPad = /ipad/i.test(navigator.userAgent.toLowerCase());
if (isiPad)
{
…
}

Detect iPhone

检测 iPhone

var isiPhone = /iphone/i.test(navigator.userAgent.toLowerCase());
if (isiPhone)
{
…
}

Detect iPod

检测 iPod

var isiPod = /ipod/i.test(navigator.userAgent.toLowerCase());
if (isiPod)
{
…
}

Detect iDevice

检测设备

var isiDevice = /ipad|iphone|ipod/i.test(navigator.userAgent.toLowerCase());

if (isiDevice)
{
…
}

Detect Andriod

检测安卓

var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

if (isAndroid)
{
…
}

Detect Blackberry

检测黑莓

var isBlackBerry = /blackberry/i.test(navigator.userAgent.toLowerCase());

if (isBlackBerry)
{
…
}

Detect WebOs

检测 WebO

var isWebOS = /webos/i.test(navigator.userAgent.toLowerCase());

if (isWebOS)
{
…
}

Detect Windows Phone

检测 Windows Phone

var isWindowsPhone = /windows phone/i.test(navigator.userAgent.toLowerCase());

if (isWindowsPhone)
{
…
}

回答by Hector Santos

Many answers here. Here is my first consideration.

这里有很多答案。这是我的第一个考虑。

Without JavaScript, including the possibility Javascript is initially disabled by the user in his browser for security purposes, to be white listed by the user if the user trusts the site, DOM will not be usable because Javascript is off.

如果没有 JavaScript,包括用户出于安全目的最初在其浏览器中禁用 Javascript 的可能性,如果用户信任该站点,则用户将其列入白名单,DOM 将无法使用,因为 Javascript 已关闭。

Programmatically, you are left with a backend server-side or frontend client-side consideration.

以编程方式,您需要考虑后端服务器端或前端客户端。

With the backend, you can use common denominator HTTP "User-Agent" request header and/or any possible proprietary HTTP request header issued by the browser to output browser specific HTML stuff.

对于后端,您可以使用通用的 HTTP“用户代理”请求标头和/或浏览器发出的任何可能的专有 HTTP 请求标头来输出浏览器特定的 HTML 内容。

With the client site, you may want to enforce Javascript to allow you to use DOM. If so, then you probably will want to first use the following in your HTML page:

对于客户端站点,您可能希望强制执行 Javascript 以允许您使用 DOM。如果是这样,那么您可能希望首先在 HTML 页面中使用以下内容:

<noscript>This site requires Javascript. Please turn on Javascript.</noscript>

While we are heading to a day with every web coder will be dependent on Javascript in some way (or not), today, to presume every user has javascript enabled would be design and product development QA mistake.

虽然我们即将面临每个网络编码人员都以某种方式(或不)依赖 Javascript 的一天,但今天,假设每个用户都启用了 javascript 将是设计和产品开发 QA 错误。

I've seen far too may sites who end up with a blank page or the site breaks down because it presumed every user has javascript enabled. No. For security purposes, they may have Javascript initially off and some browsers, like Chrome, will allow the user to white list the web site on a domain by domain basis. Edge is the only browser I am aware of where Microsoft made the decision to completely disable the user's ability to turn off Javascript. Edge doesn't offer a white listing concept hence it is one reason I don't personally use Edge.

我也看到很多网站最终会出现空白页面或网站崩溃,因为它假定每个用户都启用了 javascript。不可以。出于安全考虑,它们最初可能会关闭 Javascript,并且某些浏览器(例如 Chrome)将允许用户逐个域地将网站列入白名单。Edge 是我所知道的唯一一个浏览器,微软决定完全禁用用户关闭 Javascript 的能力。Edge 不提供白名单概念,因此这是我个人不使用 Edge 的原因之一。

Using the tag is a simple way to inform the user your site won't work without Javascript. Once the user turns it on and refreshes/reload the page, DOM is now available to use the techniques cited by the thread replies to detect chrome vs safari.

使用标记是一种通知用户您的网站在没有 Javascript 的情况下将无法运行的简单方法。一旦用户打开它并刷新/重新加载页面,DOM 现在就可以使用线程回复中引用的技术来检测 chrome 与 safari。

Ironically, I got here because I was updating by platform and google the same basic question; chrome vs sarafi. I didn't know Chrome creates a DOM object named "chrome" which is really all you need to detect "chrome" vs everything else.

具有讽刺意味的是,我来到这里是因为我正在按平台进行更新,并在 google 上搜索相同的基本问题;铬与萨拉菲。我不知道 Chrome 创建了一个名为“chrome”的 DOM 对象,这实际上是检测“chrome”与其他所有内容所需的全部。

var isChrome = typeof(chrome) === "object";

var isChrome = typeof(chrome) === "object";

If true, you got Chrome, if false, you got some other browser.

如果为 true,则使用 Chrome,如果为 false,则使用其他浏览器。

Check to see if Safari create its own DOM object as well, if so, get the object name and do the same thing, for example:

检查 Safari 是否也创建了自己的 DOM 对象,如果是,则获取对象名称并执行相同的操作,例如:

var isSafari = (typeof(safari) === "object");

var isSafari = (typeof(safari) === "object");

Hope these tips help.

希望这些提示有所帮助。

回答by Adriano Carneiro

jQuery provides that:

jQuery 规定:

if ($.browser.webkit){
    ...
}

Further reading at http://api.jquery.com/jQuery.browser/

进一步阅读http://api.jquery.com/jQuery.browser/

Update

更新

As noted in other answers/comments, it's always better to check for feature support than agent info. jQuery also provides an object for that: jQuery.support. Check the documentationto see the detailed list features to check for.

正如其他答案/评论中所述,检查功能支持总是比检查代理信息更好。jQuery 还为此提供了一个对象:jQuery.support. 检查文档以查看要检查的详细列表功能。

回答by blacksheep

Chrome 80 is just released and it comes with one amazing thing navigator.getUserAgent()function, Its promise based and returns an object with props, now no need to user Regex to detect chromium based browsers

Chrome 80 刚刚发布,它带有一个惊人的navigator.getUserAgent()功能,它基于承诺并返回一个带有道具的对象,现在不需要用户正则表达式来检测基于铬的浏览器

navigator.getUserAgent().then(val => console.log(val)).catch(err => console.log(err));

Note : make sure your chrome is v.80+

注意:确保您的 chrome 是 v.80+