How to detect chrome and safari browser (webkit)
Asked Answered
A

9

65

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!

Anoxia answered 27/9, 2012 at 16:23 Comment(15)
You can use jQuery.browser, it's just not recommended because the user agent can be spoofed. Instead, it's recommended you use feature detection, which isn't spoofable.Reprovable
Why are you trying to detect them? Likely there is a better way than using browser detection.Rubstone
@PeeHaa, you'd think... but no.Misspell
Why do you need to detect Chrome or Safari? What are you trying to do?Weatherspoon
How could it use feature detection? Two browsers with the same features would give the same results!Jacquetta
@Jacquetta although they are both webkit I'm pretty sure there are differencesPoston
@Poston You should learn how to use Google and jQuery.browser: api.jquery.com/jQuery.browser . It uses the useragent, and jQuery recommends using feature detection. jQuery.browser is deprecatedReprovable
@ianpgall Excuse me? You are telling what I should do? Did I read that correctly?Poston
@Poston — Great. So Chrome 27 doesn't support FOO but Safari does. So you decide which is which based on various things including support for FOO. Then Chrome 28 comes out and it does support FOO, so the old jQuery thinks that Chrome 28 is Safari. (And that example demonstrates why feature detection is better then browser detection and why you can't use feature detection to reliably determine browser - keeping up to date is hard)Jacquetta
@Poston If you want to post comments/answers that are correct, you should probably learn about them first, that's all...Reprovable
@Poston I took it more as "You didn't know jQuery.browser used feature detection? Wow. Just Wow." Sorry for misunderstanding!Reprovable
Webkit is the new IE6 !!!Roots
@Jacquetta feature detection will never help you work around browser quirks, which is to me the main reason to do browser detection in the first place. Feature detection addresses a very small range of problems, whereas fixing browser-specific quirks is the core of cross-browser compatibility. In that light, you should probably use feature detection once in a blue moon, when you really need to test for a feature, but you will always need to test for browser to fix that annoying Safari / IE / FF / Chrome anomaly/bug.Coverall
if you need to detect webkit browsers take a look at this: https://mcmap.net/q/112235/-detect-webkit-browser-in-javascriptCornel
A case for browser detection in 2019: in iOS Safari, there is no way to set an HTML5 Date Input to "blank". So in this case only it's good to use JS to add a manual "clear" button next to these fields. Stupid, stupid design choice by Apple, but a genuine case for browser detection.Th
E
83

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

But...

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


This fits your requirement:

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

Live Demo: 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)

Live Demo: 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)

Live Demo: 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!");
Edgardo answered 27/9, 2012 at 16:28 Comment(8)
@ wouldn't Case 3 misdetect rockmelt and chromium?Buckwheat
How would you write out case 1 for IE and FireFox?Aceae
Your demo fails under Maxthon. It recognizes it as Safari because it is webkit.Doomsday
JQuery no longer supports .Browser. This is now depreciated. See vsync's answer.Retharethink
Like .live(..) and others. I also wrote that is not recommended to use it @MichaelMikhjianEdgardo
By the way $.browser.chrome = $.browser.webkit && !!window.chrome; should be logically equivalent to $.browser.chrome = $.browser.webkit && window.chrome; I should also note that Opera now uses Webkit in newer versions, so "You are using Safari" would come up for Opera as well.Tumbleweed
Why is it bad to not use case 1? I'm looking for a pure JS version of testing for Safari (due to a bug in Safari that can't be feature tested).Communicative
"using Chrome" would come up for Opera now. Anyone has a reliable way for browser detection? (Please don't say "use feature detection". I am trying to point users to some browser that does not have bugs for the features I am using.)Jujutsu
R
72

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 Agent is beyond me.

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

The following is false in Mozilla Firefox, Microsoft Edge; it is true in Google Chrome.

"webkitLineBreak" in document.documentElement.style

Note this is not future-proof. A browser could implement the -webkit-line-break property 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 webkit prefix and check for that to be missing in other browsers.

Roots answered 9/5, 2013 at 10:27 Comment(9)
This doesn't work if the browser claims to support a feature, but supports it differently than other browsers.Th
If you need stronger feature-detection then mixing more than one test will make it so. You need to pick a feature you are certain of and know how it behaves on other browsers, and not some random one.Roots
Example: the HTML5 “date” input type. On iOS WebKit, there is no way to blank the field; so I have to manually add a “clear” button. Safari claims to understand Date, but it handles it incorrectly. I can’t think of any way to see who does it right via feature detectionTh
@StephenR - what you're talking about isn't feature detection, but is implementation-detection, which is another subject.Roots
What I’m talking about is detecting the one browser that I know does it differently from all others! ;-)Th
well some properties like "scrollSnapAlign" are true in moz and webkit browsers but only work properly in webkit.Shaer
@ImranBughio - what is your point? My method in this answer has nothing to do with detecting specific feature or its "implementation correctness". It is a method to detect Chrome/webkit. It is up to you to pick a random property, anything you desire, which you believe to be unique to that vendor.Roots
@Roots I was replying to your text: Instead of detecting a browser, you should rather detect a feature, that not all features are useful to be detected like the one I mentioned and hence in such scenarios detecting browsers becomes useful.Shaer
@ImranBughio - but this topic here is only about detecting Chrome. For detecting features you should try to find another stackoverflow question, this is not the place and I intentionally did not get into feature-detection because it's a whole different subject. Read more hereRoots
D
11

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

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 WebKit check which does not use 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:

var isWebKit = 'WebkitAppearance' in document.documentElement.style;
Doomsday answered 27/9, 2012 at 16:25 Comment(9)
you can search for these features: https://mcmap.net/q/112236/-is-the-a-specific-webkit-feature-i-can-detect-to-check-if-a-user-is-using-a-webkit-browser (mind that they keep changing, so a test might fail in a year)Roots
While you're right that this is the best thing to do, it's not always possible. For example, webkit browsers contain a bug that I wish to work around that I cannot easily check. I'm pretty much stuck with checking the user agent.Wordsworth
@Wordsworth Yes there are such cases. I have updated the answer with a check which is independent of user agent.Doomsday
Your check is nice, but probably not future proof, as eventually webkitURL will be replaced with URL.Wordsworth
window.webkitURL is not supported by older versions of safari (before 6.0) and chrome (before 8.0)Cornel
Could you please update your answer with '(WebkitAppearance' in document.documentElement.style) instead. As per @Cornel webkitURL is not really old enough to be used. WebkitAppearance is true since Safari 3.0 (when split from the -khtml- prefix) as well as Chrome 1.0 or Webkit 522. Appearance is far from being implemented, since it was dropped from CSS3 Specs. In addition it is currently "non-standard" as well as "not on a standards track" at this time. So WebkitAppearance will be around for a very long time...Egregious
This answer is not correct. Modernizr will not tell you about browser specific bugs, and there is much more to compatibility than just feature detection. use feature detection when you want to detect features, use browser detection when you're looking to fix browser-specific glitches.Coverall
Code working around specific browser bugs requires browser detection, but should also be removed once the browser bug is fixed. The general case is not specific browser bugs but features and thus my answer is about feature detection.Doomsday
WebkitAppearance does not work for me. Firefox is detected as well. MDN explains ff and ie support it for compat reasons developer.mozilla.org/en-US/docs/Web/CSS/appearanceSymbolize
M
9

There is still quirks and inconsistencies in 2019.

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

None of the answer of this topic are working any more. (maybe those with 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!

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

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:

@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.

List of possible -moz- only rules.

Can I use css support?

Mudskipper answered 13/2, 2019 at 9:46 Comment(0)
C
3

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

Contribute answered 7/5, 2013 at 17:4 Comment(3)
Unfortunately new MS browser Edge lies in UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240" and this behavior is officially confirmed hereCohere
Most of the solutions like window.webkitURL and 'WebkitAppearance' will not exclude Edge either.Glassy
You can filter out edge by just (/WebKit/.test(navigator.userAgent) && !/Edge/.test(navigator.userAgent))Curiel
J
2

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

Use jQuery.browser

I thought we are not supposed to use 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.

Jacquetta answered 27/9, 2012 at 16:28 Comment(0)
R
1

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.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

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

Detect iPhone

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

Detect 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

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

if (isWebOS)
{
…
}

Detect Windows Phone

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

if (isWindowsPhone)
{
…
}
Rollie answered 6/5, 2014 at 11:33 Comment(3)
if i is case insensitive in regex, why would you add toLowerCase to all the UAs?Capsulate
Just so you don't have to write "blackberry" or "windows phone" or any thing else case sensitive , now everyone knows where it should be uppercase or lowercase so its more straightforward as i think.Rollie
you don't get it HasanIrbm
J
1

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.

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.

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:

<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.

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.

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.

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.

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

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

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:

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

Hope these tips help.

Jolynnjon answered 14/1, 2019 at 16:36 Comment(1)
Edge has window.chrome as well so this doesn't help.Leontine
P
0

jQuery provides that:

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

Further reading at 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 documentation to see the detailed list features to check for.

Padnag answered 27/9, 2012 at 16:25 Comment(1)
Note that this is deprecated.Rubstone

© 2022 - 2024 — McMap. All rights reserved.