Jquery как определить браузер сафари
I have 5 addons/extensions for FF, Chrome, IE, Opera, and Safari.
How can I recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?
I'd like to re-surface this question - is there a reliable & simple answer to this yet? There are many (old) questions like this on SO and yet most of them work off the userAgent function which even w3schools acknowledges is inaccurate. I've tested some of the answers to this question and similar ones, and none of them seem reliable. If I'm better off asking a new question please let me know.
28 Answers 28
Googling for browser reliable detection often results in checking the User agent string. This method is not reliable, because it's trivial to spoof this value.
I've written a method to detect browsers by duck-typing.
Only use the browser detection method if it's truly necessary, such as showing browser-specific instructions to install an extension. Use feature detection when possible.
Analysis of reliability
The previous method depended on properties of the rendering engine ( -moz-box-sizing and -webkit-transform ) to detect the browser. These prefixes will eventually be dropped, so to make detection even more robust, I switched to browser-specific characteristics:
- Internet Explorer: JScript's Conditional compilation (up until IE9) and document.documentMode .
- Edge: In Trident and Edge browsers, Microsoft's implementation exposes the StyleMedia constructor. Excluding Trident leaves us with Edge.
- Edge (based on chromium): The user agent include the value "Edg/[version]" at the end (ex: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36 Edg/80.0.361.9").
- Firefox: Firefox's API to install add-ons: InstallTrigger
- Chrome: The global chrome object, containing several properties including a documented chrome.webstore object.
- Update 3 chrome.webstore is deprecated and undefined in recent versions
- Safari: A unique naming pattern in its naming of constructors. This is the least durable method of all listed properties and guess what? In Safari 9.1.3 it was fixed. So we are checking against SafariRemoteNotification , which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards.
- Opera: window.opera has existed for years, but will be dropped when Opera replaces its engine with Blink + V8 (used by Chromium).
- Update 1: Opera 15 has been released, its UA string looks like Chrome, but with the addition of "OPR". In this version the chrome object is defined (but chrome.webstore isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose.
- Update 2: !!window.opr && opr.addons can be used to detect Opera 20+ (evergreen).
- Blink: CSS.supports() was introduced in Blink once Google switched on Chrome 28. It's of course, the same Blink used in Opera.
Successfully tested in:
- Firefox 0.8 - 61
- Chrome 1.0 - 71
- Opera 8.0 - 34
- Safari 3.0 - 10
- IE 6 - 11
- Edge - 20-42
- Edge Dev - 80.0.361.9
Though both are Webkit based browsers, Safari urlencodes quotation marks in the URL while Chrome does not.
Therefore I need to distinguish between these two in JS.
Is there a better method or do I just stick with the deprecated value for now?
I don't know if sticking with it is such a good idea, I haven't checked this out in depth, although I just browsed to the $.browser docs on chrome and it flags $.browser.safari === true . eeek.
possible duplicate of How to detect Safari, Chrome, IE, Firefox and Opera browser without user agent sniffing?.
14 Answers 14
Using a mix of feature detection and Useragent string:
Usage:
if (is_safari) alert('Safari');
Or for Safari only, use this :
With a ratio of 48 votes vs. 5 votes for a feature detection with side effects, apparently this is the recommended solution. :) Making it accepted answer.
Chrome/Windows will report as Safari: (Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36)
The following identifies Safari 3.0+ and distinguishes it from Chrome:
For checking Safari I used this:
It works correctly.
Apparently the only reliable and accepted solution would be to do feature detection like this:
Feature detection is the way to go, but there's a better method which does not have any side effects. Your snippet may interfere with other scripts which rely on hash change events. I've marked the question as a duplicate of this. I've created and tested the method in Safari 3.0 - 5.1.3 (Mac and Windows). It's a one-liner :)
If you are checking the browser use $.browser . But if you are checking feature support (recommended) then use $.support .
You should NOT use $.browser to enable/disable features on the page. Reason being its not dependable and generally just not recommended.
If you need feature support then I recommend modernizr.
Feature detection is great, but what about when you want to stop a particular browser from using CSS Animations (for example), because it has a buggy implementation? It technically supports the feature, but we want to take a decision to disable it for that browser, because the experience is better without in that instance.
This will determine whether the browser is Safari or not.
I use to detect Apple browser engine, this simple JavaScript condition:
A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.
Using jQuery it goes like this:
This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.
My best solution
Not the answer you're looking for? Browse other questions tagged javascript jquery browser-detection or ask your own question.
Linked
Related
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.5.11.42086
How to detect Safari browser using JavaScript? I have tried code below and it detects not only Safari but also Chrome browser.
You should almost certainly be testing for whatever differences in the APIs there are. There are other WebKit based browsers beyond Safari and Chrome.
There are many reasons one might wish to detect the browser. For example, as of this writing certain aspects of the SVG engine such as filters are broken in Safari, but working in Chrome.
Sometimes you just can't fix bug because you can't reproduce it(I don't have access to Mac). I fixed problem on Midori(some BlobBuilder/Blob issue for sendAsBinary shim), but client says there is still an issue with file upload, so the best thing i can think of is just to remove Safari support and use iframes for it(as for old IE)
23 Answers 23
Note: always try to detect the specific behavior you're trying to fix, instead of targeting it with isSafari?
As a last resort, detect Safari with this regex:
It uses negative look-arounds and it excludes Chrome, Edge, and all Android browsers that include the Safari name in their user agent.
That's because all browsers on iOS are just wrappers for Safari (with the exception of Opera Mini in Mini mode), including Chrome. This doesn't necessarily mean that they'll all match this test since the userAgent string is up to the wrapper. You might want to detect Chrome on iOS separately.
Dude this worked for me. Thanks a ton.. navigator.userAgent was returning values like "5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36" for both Chrome in Windows and Safari in mac.
Fixed now. You're definitely right, the problem with a lot of browsers is that they include other names to try not to be left out. Like Edge includes both Chrome and Safari in its UA. User agent checks are bad for this reason: browsers change and the checks need to be updated. Unfortunately there's no perfect way to detect a browser, it's always a guess.
Definitely a good idea to use feature detection, but some behaviors are just hard or nearly impossible to test, for example whether videos on mobile go automatically fullscreen, something that only happens on the iPhone and iPod. To test it, you need to load a video and have the user play it.
You can easily use index of Chrome to filter out Chrome:
Doesn't work. Currently outputting chrome UA string on iPhone and it doesn't even have the word "chrome" in it.
@Flimm There are many legitimate use cases for browser detection. Do not presume to know the asker or answerer's intention. While it's great to include a helpful tip you may believe to be relevant, it's by no means a requirement.
As other people have already noted, feature detection is preferred over checking for a specific browser. One reason is that the user agent string can be altered. Another reason is that the string may change and break your code in newer versions.
If you still want to do it and test for any Safari version, I'd suggest using this
This will work with any version of Safari across all devices: Mac, iPhone, iPod, iPad.
Edit 2
Updated according to Chrome docs to detect Chrome on iOS correctly
It's worth noting that all Browsers on iOS are just wrappers for Safari and use the same engine. See bfred.it's comment on his own answer in this thread.
Edit 3
Updated according to Firefox docs to detect Firefox on iOS correctly
Unfortunately there's more more reasons to try to figure out the browser than just feature detection. A browser can support a feature, but be buggy (ex: canvas bug in IE10, but the same feature works in IE9). Also Firefox behaves differently than webkit based browsers, such as how it responds to mouse movement. Apple's Safari has reflow bugs that don't exist in Chrome. Some browsers are also performant when doing certain computationally intensive tasks than others.
Not sure why this isnt higher up - is this is perfect, short, and simple. I needed to rule out desktop safari for the lack of getUserMedia .
This code is used to detect only safari browser
this code only detects wether a webkit browser is not chrome. Many other browsers have the bad idea of including "safari" in their user agent string. For example, Opera: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36 OPR/24.0.1558.51 (Edition Next) , or Stock Android browser: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.34 Safari/534.24
I just checked a half dozen third party iOS browsers, they all spoof the very exact Safari User-Agent.
So this will only detect Chrome. And yet, I just found out Chrome 44 no longer has Chrome in the UA, but 'CriOS' instead :(
We should always try to do feature detection, and use browser detection as a last resort, since the latter is much more likely to break and to block legitimate users. Any answer which doesn't mention feature detection at all is getting a downvote from me.
Because userAgent for chrome and safari are nearly the same it can be easier to look at the vendor of the browser
Safari
Chrome
FireFox (why is it empty?)
IE (why is it undefined?)
I was looking for something to disable warning messages in safari at work on various computers (mac desktops, ipads, etc), and this worked perfectly.
Most brilliant and easiest solution. Usually you want to catch Safari, since it is the newer IE - to fix javascript things it does not support - like it should. Even Chrome in iOS is based on Safari-engine and got the same bad support as Safari. And this in a simple way, detects Safari in Mac OS, Safari and Chrome in iOS. Splendid.
Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox & Opera (desktop and iOS versions). First we need to detect Apple vendor and then exclude Chrome, Firefox & Opera (for iOS).
I don't know why the OP wanted to detect Safari, but in the rare case you need browser sniffing nowadays it's problably more important to detect the render engine than the name of the browser. For example on iOS all browsers use the Safari/Webkit engine, so it's pointless to get "chrome" or "firefox" as browser name if the underlying renderer is in fact Safari/Webkit. I haven't tested this code with old browsers but it works with everything fairly recent on Android, iOS, OS X, Windows and Linux.
- All browsers under iOS will be reported as "safari/webkit"
- All browsers under Android but Firefox will be reported as "chrome/blink"
- Chrome, Opera, Blisk, Vivaldi etc. will all be reported as "chrome/blink" under Windows, OS X or Linux
Old versions of IE have the string MSIE not Trident. Sometimes edge is missing the final e in the word edge. You have to search for edg
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!
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.
@PeeHaa — 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)
10 Answers 10
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.
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)
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)
Case 3: (Using jQuery and $.browser, "elegant" solution)
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.
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.
This doesn't work if the browser claims to support a feature, but supports it differently than other browsers.
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.
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 detection
@StephenR - what you're talking about isn't feature detection, but is implementation-detection, which is another subject.
What I’m talking about is detecting the one browser that I know does it differently from all others! ;-)
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 :
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:
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.
Your check is nice, but probably not future proof, as eventually webkitURL will be replaced with URL.
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.
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 anymore. (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.
Beware to not use it in loops, for performance it's better to populate a constant on load:
Using CSS only, the above would be:
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 here
I am trying to detect the chrome and safari browser using jquery or javascript.
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.
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.
Example Usage:
Detect iPad
Detect iPhone
Detect iPod
Detect iDevice
Detect Andriod
Detect Blackberry
Detect WebOs
Detect Windows Phone
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.
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 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:
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:
Как определить браузер Safari с помощью JavaScript? Я пробовал код ниже, и он обнаруживает не только Safari, но и браузер Chrome.
вы можете легко использовать индекс Chrome для фильтрации Chrome:
в крайнем случае, обнаружение Safari с помощью этого регулярного выражения:
Он использует отрицательный взгляд-вокруг и он исключает Chrome, Edge и все браузеры Android, которые включают Safari имя в их агенте пользователя.
Как уже отмечали другие люди, обнаружение функций предпочтительнее, чем проверка конкретного браузера. Одна из причин заключается в том, что строка агента пользователя может быть изменена. Другая причина заключается в том, что строка может изменить и сломать ваш код в новых версиях.
Если вы все еще хотите сделать это и протестировать любую версию Safari, я бы предложил использовать это
Это будет работать с любой версией Safari на всех устройствах: Mac, iPhone, iPod, устройство iPad.
редактировать
Изменить 2
Обновлено в соответствии с Chrome docs для правильного обнаружения Chrome на iOS
стоит отметить, что все браузеры на iOS-это просто обертки для Safari и используют один и тот же движок. См. bfred.это комментарий к его собственному ответу в этой теме.
редактировать 3
Обновление ПО Firefox docs для правильного обнаружения Firefox на iOS
этот код используется для обнаружения только браузера safari
поскольку userAgent для chrome и safari почти одинаковы, может быть проще посмотреть на поставщика браузера
сафари
Chrome
в Firefox (почему он пустой?)
IE (почему это не определено?)
только сафари whitout Chrome:
после попытки других кодов я не нашел никаких, которые работают с новыми и старыми версиями Safari.
наконец, я сделал этот код, который работает очень хорошо для меня:
Я использую этот
изменено регулярное выражение для ответа выше
Я знаю, что этот вопрос старый, но я думал о публикации ответа в любом случае, поскольку это может помочь кому-то. В некоторых случаях вышеперечисленные решения терпели неудачу, поэтому нам пришлось реализовать его таким образом, чтобы обрабатывать iOS, Desktop и другие платформы отдельно.
эта уникальная "проблема" - это 100% знак того, что браузер Safari (верьте или нет).
это означает, что дескриптор объекта cookie имеет значение false в Safari, а все остальные-true, что на самом деле дает мне головную боль в другом проекте. Удачи в кодировании!
может быть, это работает :
EDIT: БОЛЬШЕ НЕ РАБОТАЕТ
Я заметил, что только одно слово отличает Safari - "версия". Таким образом, это регулярное выражение будет работать идеально:
Я не знаю, почему OP хотел обнаружить Safari, но в редком случае вам нужно обнюхивать браузер в настоящее время, вероятно, более важно обнаружить движок рендеринга, чем имя браузера. Например, в iOS все браузеры используют движок Safari/Webkit, поэтому бессмысленно получать "chrome" или "firefox" в качестве имени браузера, если базовый рендеринг на самом деле Safari/Webkit. Я не тестировал этот код со старыми браузерами, но он работает со всем довольно недавним на Android, iOS, OS X, Windows и Linux.
Читайте также: