Как определить браузер js
Как-то потребовалось создать функцию, принимающую объект json со следующим форматом записи: "браузер":то, что следует вернуть, иначе говоря такую функцию, которая бы возвращала указанный объект в зависимости от браузера пользователя.
ТЗ, которое я для себя определил:
- браузеры можно группировать, указывая их через пробел
- браузерам можно задавать версию (ie6,opera10)
- браузерам можно задавать полную версию (opera10.15)
- поддержка самых популярных браузеров
Мой способ гарантированно не самый точный, так как он используют свойство userAgent объекта navigator, которое при желании подделывается, но с другой стороны любой способ проверки клиента как серверный, так и клиентский можно обойти. Так же встает вопрос о надобности такой "подделки", тем более мало какие роботы исполняют javascript код.
В случае если ни одного выражение не совпадает с браузером пользователя, возвращается "none", которое можно также указать как свойство передаваемого объекта.
Пример использования: (данный код повернет на 25 градусов все содержимое страницы в любом современном браузере)
Название браузера нужно вводить в следующем формате : ie, firefox, opera, chrome, safari, konqueror, iceweasel, seamonkey. Регистр неважен. Версия пишется слитно с название, пример: ie7. Если для нескольких браузеров должно возвратиться одно и тоже значение, вы просто указываете их через пробел, как
на примере ("chrome safari":"WebkitTransform"). В качестве возвращаемого значения может выступать любой объект JavaScript (строка, число, функция, логическое значение и т.д.)
Зачем проверять версию браузера и юзерагент, когда надо проверять то, что он умеет. Тем более, что ваш код даст огромную погрешность. Да и многие браузеры неправильно отдают свой агент.
Я перечислил какие браузеры поддерживаются, они не будут "неправильно" отдавать свой юзер-агент. И версия для каждого браузера определяется по индивидуальному правилу. Мне так же интересно, как вы будете проверять то, что умеет браузер, с большей пользой, когда любое свойство можно подменить, как и юзер-агент.
Это они на текущий момент не будут неправильно отдавать юзер-агент. Но никто не может поручиться за то, что будет завтра.
Конечно, проверять надо поддержку браузером конкретных свойств и методов. Путаница в юзер-агентах — правило, а неправильное определение стандартных свойств и методов — редкое исключение и косяк.
юзерагент без затей меняется, например в фаерфоксе без всяких бубнов, в системных параметрах браузера. к сожалению предложенный вами способ ненадежен и необъективен
В Opera он тоже легко подменяется в параметре Custom User Agent в opera:config. Там же меняется и navigator.appName.
судя по скрипту, он ищет непонятно где, не ясно что. где сам источник версии браузера, откуда берутся аргументы?
Спасибо! Везде работает кроме IE. :D (ie 6-ка)
IE Стабилен, как всегда
Спасибо за понятный и прозрачный код.
Не понимаю зачем было разводить флейм на тему ненадежности метода. 90% пользователей вообще не знают про строку юзерагента, а те, кто знают, изменяя эту строку, сами себе становятся злобными буратинами.
Автору зачет, респект и уважуха.
Все течет, все меняется - в IE10 данная функция работать не будет, потому что она ищет в userAgent подстроку "MSIE", а десятый ослик userAgent отдает вот такой: "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; rv:11.0) like Gecko". Т.е. надо добавить поиск по названию IE-шного движка - Trident.
Спс большое за мануал!
вах вах вах. в IE10 зер гуд как работает у меня. Вот в IE11 не работает. Пришлось немного отсебятины сделать.
Author thank you very much!
Вот, переделал под современные реалии и улучшил юзабилити:
Результат выполнения функции:
Определение мобильных браузеров не поддерживается, но для них возвращается platform: "mobie".
Konqueror, Iceweasel, SeaMonkey выкинул за ненадобностью. Кому нужно их определять в 2016 году даже представить не могу.
How do I determine the exact browser and version using JavaScript?
+1: good question because of suggested detection of feature support rather than extraction of name and version in answers.
25 Answers 25
As the name implies, this will tell you the name and version number supplied by the browser.
It is handy for sorting test and error results, when you are testing new code on multiple browsers.
+1 from me as well. Sometimes, it's not about feature support, it's actually about the browser. Yes, the user-agent info can be spoofed, but when you're dealing with older browsers and circumventing their bugs (like FF 3's issue with not sending the Content-Length header for read-only AJAX POST messages), feature support just doesn't cut it.
I love this! Thanks man! Still, I just made a modification on the first and second last line. I replaced: navigator.sayswho= with navigator.browserInfo= on the 1st line for better readability (i.e. so I won't wonder months later what it does in the code) and replaced return M.join(' '); with return < 'browser': M[0], 'version': M[1] >; so that I can use it like this in the global scope: console.log(navigator.browserInfo.browser); and console.log(navigator.browserInfo.version); for better accessibility. Sorry I guess I did mess with it even though it said "Don't touch".
Tested on chrome only for time being. if you wish to get the full version number, change the regx to (vivaldi|opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([0-9|\.]+) difference is the last bracket instead of (d+) it should be ([0-9|\.]+) so number and the dot. also added vivaldi browser just incase :)
You can use simply say:
This is something I wrote to get client info
isn't it a little wasteful to always run all checks? seems pointless to check for Linux if you know it's a Windows isn't it.
@Matthias, thanks for the suggestion. I'll try to optimize the solution. The same logic can be applied in testing for browsers also.
@ArunPJohny: +1, for those horrible, rare times when you have no choice but to browser detect rather than feature detect. Do you keep this up to date, maybe in an OS project somewhere? Obviously since you wrote this answer, IE's stopped saying MSIE for instance.
all i see is var var var var var var . Please, future coders who see this, don't do this. It's really not necessary and is a pain for project managers with OCD's to read.
Here's how to detect browsers in 2016, including Microsoft Edge, Safari 10 and detection of Blink:
The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.
The only correct answer in this page. Navigator object is no longer reliable after latest IE versions.
It is usually best to avoid browser-specific code where possible. The JQuery $.support property is available for detection of support for particular features rather than relying on browser name and version.
In Opera for example, you can fake an internet explorer or firefox instance.
Now deprecated according to jQuery.
We strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support .
When coding websites, I always make sure, that basic functionality like navigation is also accessible to non-js users. This may be object to discussion and can be ignored if the homepage is targeted to a special audience.
Sometimes you really need to know the browser, when the same features are supported in a different way. So, if making use of jQuery, $.browser is the right way, as indicated by user288744
Sometimes you do need to know the browser version. Please make sure to answer the question that was asked.
@PhilRykoff - but you're not answering the 99% case of the question - you're answering the 99% case of another question, that you assume the questioner meant to ask, or should have asked. Maybe ask for clarification first?
@Phil, you're right that sometimes the best answer is one that the questioner didn't even ask. However, I disagree with your application of that theory to this question. Consider window.onpopstate (and please remember that a non-jQuery answer is most ideal to a question that never mentions jQuery) -- IE does not fire it for the initial view, in contrast to other browsers. Sometimes, to be robust, you must consider what browser you are dealing with to implement a feature correctly. Given the title of this question, that is precisely the information one would expect, and yours does not.
Uh, I hate to say this, but WHEN apart from testing your code with multiple browsers for compatibility purposes will you otherwise spoof your browser's configuration?
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
I've been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but not the version.
How can I detect the version of a browser like this?
You can use UAParser JavaScript Library to detect browser and its version. I did it following this How to detect browser, engine, OS, CPU, and device using JavaScript?
32 Answers 32
You can see what the browser says, and use that information for logging or testing multiple browsers.
It would be helpful if this answer included output examples. I can't tell what strings to expect from the function.
This script incorrectly reports browser Chrome version 4.0 for the internal Facebook browser (launched when you click web links within the Facebook app on Android). The useragent string looks something like: Mozilla/5.0 (Linux; Android 5.0; Nexus 9 Build/LRX21R; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/45.0.2454.95 Safari/537.36 [FB_IAB/FB4A;FBAV/50.0.0.10.54;] This is a very prominent user agent unfortunately so can't really ignore it.
There are libraries that do this, viz bowser, and as a general rule you shouldn't reinvent the wheel if you don't have to.
This is an improvement on Kennebec's answer.
This way you can shield yourself from the obscurity of the code.
get_browser and get_browser_version return incorrect details inside the 'if trident' and 'if chrome' conditionals if tem!=null
Here are several prominent libraries that handle browser detection as of May 2019.
Bowser by lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB
*supports Edge based on Chromium
Platform.js by bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB
jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB
Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB
Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B
Notable Mentions:
-
- 1,355★s - Last updated Oct 2, 2018 - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
Further Reading
This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:
- Maintains original answer's minimal code. (K)
- Works with Microsoft Edge (K)
- Extends the navigator object instead of creating a new variable/object. (K)
- Separates browser version and name into independent child objects. (H)
The bowser JavaScript library offers this functionality.
It seems to be well maintained.
Outdated reference, no longer supported -"This page used to contain my own browser detect script, but I found that I do not have enough time to keep it up to date. Therefore I removed it."
I was looking for a solution for myself, since jQuery 1.9.1 and above have removed the $.browser functionality. I came up with this little function that works for me. It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddle to illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.
To check if the current browser is Opera you would do
Edit Fixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browser keys doesn't matter. Updated jsFiddle link.
2015/08/11 Edit Added new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddle link.
Существует достаточно большое количество браузеров, а также их версий. И проблема в том, что одни браузеры позволяют выполнить определённый скрипт, а другие не позволяют. Встаёт вопрос: а как узнать браузер пользователя в JavaScript, чтобы через условие решить: надо выполнять скрипт или нет. И о том, как определить имя и версию браузера пользователя я и напишу в этой статье.
Для таких целей существует объект Navigator, а точнее два его свойства: appName и appVersion. Давайте для начала выведем название браузера пользователю:
document.write("Вы используете браузер " + navigator.appName);
В результате Вы увидите имя браузера пользователя. Также огромное значение оказывает не только сам браузер, но и его версия. И для таких случаев используется свойство appVersion:
document.write("Версия Вашего браузера " + navigator.appVersion);
Свойства appName и appVersion доступны только для чтения (это и логично), поэтому изменить их у Вас не получится. Теперь встаёт вопрос, а как использовать их в операторе IF:
var browser = navigator.appName;
if (browser == "NetScape")
document.write("Тут можно выполнять скрипты для обладателей браузеров NetScape");
Надеюсь, что я ответил на Ваш вопрос: "Как узнать имя и версию браузера в JavaScript".
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
Она выглядит вот так:
Комментарии ( 10 ):
И для FFox напишет Netscape
Проблем при определении браузера много, чтобы узнать, что это chrome, нужно анализировать navigator.appVersion. Для других браузеров могут быть другие свойства (appName или appCodeName).
Ну и как это сделать?
Выведите сначала, посмотрите на значение, а дальше используйте функции для работы со строками.
Ну я уже понял как.
Читайте также: