- Как Определить Мобильное Устройство с Помощью JavaScript
- Как определить Safari
- Как использовать «mobile-detect.js»
- Navigator.userAgent
- Syntax
- Value
- dongerardor / check mobile user agent
- Объект Navigator в JavaScript – информация о браузере
- Свойства и методы объекта navigator
- Пример
- Обнаружение браузера с помощью userAgent
- Определение мобильного устройства посредством userAgent
- Объект geolocation
- Получение текущего местоположения пользователя
- Методы watchPosition и clearWatch
- Browser detection using the user agent
- Considerations before using browser detection
- Avoiding user agent detection
- Browser version
- Rendering engine
- Rendering engine version
- Mobile, Tablet or Desktop
Как Определить Мобильное Устройство с Помощью JavaScript
Сегодня вы научитесь определять мобильное устройство при помощи JavaScript. Затем реализуем это при помощи «mobile-detect.js». Он может также определять операционную систему и текущий браузер, используемый пользователем.
Самый простой способ определить мобильное устройство с помощью JavaScript — это извлечь строку из navigator.userAgent . Будем искать совпадения на мобильные устройства. Если найдём совпадения в строке, то это будет одно из следующих устройств.
Как определить Safari
Для примера, определим Safari браузер с помощью JavaScript.
Теперь рассмотрим, как можно извлекать необходимую информацию при помощи «mobile-detect.js»
Как использовать «mobile-detect.js»
Mobile-detect.js использует тот же метод, но также предоставляет функции API для легкого получения необходимой информации.
Использовать mobile-detect.js очень просто. Сначала импортируйте библиотеку на свою страницу.
А затем передайте строку userAgent в конструктор.
При помощи объекта определения мобильных устройств, вы можете использовать различные методы для получения информации. Вы можете определять операционные системы — используя os() , и определять веб-браузер — используя userAgent() .
Метод phone() вернёт null , если пользователь использует планшет.
Аналогично, если пользователь использует мобильный телефон, тогда метод tablet() вернет null .
Метод mobile() показывает результат из метода phone() или tablet() . Все они будут null , если пользователь использует Компьютер.
Сегодня мы научились определять мобильные устройства. Мы рассмотрели лишь базовое использование. Ссылка на документацию.
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.
Источник
Navigator.userAgent
The Navigator.userAgent read-only property returns the user agent string for the current browser.
Note: The specification asks browsers to provide as little information via this field as possible. Never assume that the value of this property will stay the same in future versions of the same browser. Try not to use it at all, or only for current and past versions of a browser. New browsers may start using the same UA, or part of it, as an older browser: you really have no guarantee that the browser agent is indeed the one advertised by this property.
Also keep in mind that users of a browser can change the value of this field if they want (UA spoofing).
Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable. For example:
- In Firefox, you can change the preference general.useragent.override in about:config . Some Firefox extensions do that; however, this only changes the HTTP header that gets sent, and doesn’t affect browser detection performed by JavaScript code.
- Opera 6+ allows users to set the browser identification string via a menu.
- Microsoft Internet Explorer uses the Windows registry.
- Safari and iCab allow users to change the browser user agent string to predefined Internet Explorer or Netscape strings via a menu.
Syntax
Value
A DOMString specifying the complete user agent string the browser provides both in HTTP headers and in response to this and other related methods on the Navigator object.
The user agent string is built on a formal structure which can be decomposed into several pieces of info. Each of these pieces of info comes from other navigator properties which are also settable by the user. Gecko-based browsers comply with the following general structure:
Источник
dongerardor / check mobile user agent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
var isMobile = < |
Android: function() < |
return navigator.userAgent.match(/Android/i); |
>, |
BlackBerry: function() < |
return navigator.userAgent.match(/BlackBerry/i); |
>, |
iOS: function() < |
return navigator.userAgent.match(/iPhone|iPad|iPod/i); |
>, |
Opera: function() < |
return navigator.userAgent.match(/Opera Mini/i); |
>, |
Windows: function() < |
return navigator.userAgent.match(/IEMobile/i); |
>, |
any: function() < |
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows()); |
> |
>; |
window.onload = checkMobile; |
function checkMobile () < |
var browserType = isMobile.any()?»mobile»:»not mobile»; |
document.getElementById(«output»).innerHTML = browserType; |
> |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник
Объект Navigator в JavaScript – информация о браузере
На этом уроке мы познакомимся с объектом navigator , который предназначен для получения различной информации о браузере.
Объект navigator предназначен для предоставления подробной информации о браузере, который пользователь использует для доступа к сайту или веб-приложению. Кроме данных о браузере, в нём ещё содержится сведения о операционной системе, сетевом соединении и др.
Объект navigator – это свойство window :
Свойства и методы объекта navigator
Объект navigator имеет свойства и методы. Очень часто они используется для того чтобы узнать, какие функции поддерживаются браузером, а какие нет.
Свойства объекта navigator :
- appCodeName – кодовое имя браузера;
- appName – имя браузера;
- appVersion — версия браузера;
- cookieEnabled — позволяет определить включены ли cookie в браузере;
- geolocation — используется для определения местоположения пользователя;
- language — язык браузера;
- online — имеет значение true или false в зависимости от того находиться ли браузер в сети или нет;
- platform — название платформы, для которой скомпилирован браузер;
- product — имя движка браузера;
- userAgent — возвращает заголовок user agent , который браузер посылает на сервер.
Методы объекта navigator :
- javaEnabled – позволяет узнать, включён ли в браузере Java;
- sendBeacon — предназначен для отправки небольшого количества информации на веб-сервер без ожидания ответа.
Пример
Например, выведем все свойства и методы объекта Navigator на веб-страницу:
Обнаружение браузера с помощью userAgent
userAgent — это строка, содержащая информацию о браузере, которую он посылает в составе заголовка запроса на сервер.
Пример содержания строки userAgent в браузере Google Chrome:
Она содержит сведения об операционной системе, браузере, версиях, платформах и т.д.
Эти данные можно использовать, например, для обнаружения браузера. Для этого можно написать следующую функцию:
Зачем это нужно? Например для того, чтобы запускать некоторые скрипты или функции только в определенном браузере.
Но при использовании navigator.userAgent следует иметь в виду, что эта информация не является 100% достоверной, поскольку она может быть изменена пользователем.
Вообще не существует 100% надежных способов идентификации браузера. Поэтому лучше проверять доступность необходимой функции или свойства, и если этой поддержки нет, то написать обходной код для реализации этого функционала или вообще его не предоставлять для этих браузеров.
Определение мобильного устройства посредством userAgent
Самый простой способ обнаружить мобильные устройства — это найти слово mobile в пользовательском агенте ( userAgent ):
Более подробный вариант идентификации мобильного браузера:
Объект geolocation
Объект geolocation предназначен для определения местоположения устройства. Доступ к этому объекту осуществляется через свойство « navigator.geolocation »:
Узнать поддерживает ли браузер геолокацию, можно посредством проверки существования свойства geolocation в объекте navigator :
При этом, когда сайт или веб-приложение пытается получить доступ к местонахождению пользователя, браузер из соображений конфиденциальности предоставит его только в том случае если это разрешит пользователь.
Получение текущего местоположения пользователя
Получение текущего местоположения пользователя осуществляется через метод getCurrentPosition .
Этот метод посылает асинхронный запрос. В случае успеха мы можем получить местоположение устройства, в противном случае – нет.
Метод getCurrentPosition принимает 3 аргумента:
- success — функцию обратного вызова, которая будет вызвана при успешном получении геоданных (т.е. когда пользователь разрешил доступ сайту или веб-приложению к Geolocation API и данный API определил местоположение пользователя);
- error — функцию обратного вызова, которая вызывается при ошибке (т.е. когда пользователь не разрешил доступ к Geolocation API, или данный API не смог определить местонахождение пользователя, или истекло время ожидания timeout );
- options — объект, содержащий настройки.
В options можно установить:
- maximumAge — следует ли информацию о местонахождении пользователя кэшировать (в миллисекундах) или пытаться всегда получать реальное значение (значение 0 — по умолчанию);
- timeout — максимальное время в миллисекундах в течении которого нужно ждать ответ (данные о местоположении); если ответ за указанное время не пришёл, то вызывать функцию обратного вызова error (по умолчанию имеет значение infinity , т.е. ждать бесконечно);
- enableHighAccuracy — при значении true будет пытаться получить наилучшие результаты, т.е. более точное местоположение (для этого может понадобиться задействовать GPS), что в свою очередь может привести к более длительному времени отклика или увеличению энергопотребления; по умолчанию — false .
В функцию success передаётся в качестве первого аргумента объект GeolocationPosition . Он содержит информацию о местоположении устройства ( coords ) и времени, когда оно было получено ( timestamp ).
Объект coords содержит следующие свойства:
- latitude — широта (в градусах);
- longitude — долгота (в градусах);
- altitude — высота над уровнем моря (в метрах);
- speed — скорость устройства в метрах в секунду; это значение может быть null .
Пример получения местоположения устройства:
Методы watchPosition и clearWatch
Метод watchPocation используется когда нужно получать данные о местоположении каждый раз, когда оно меняется. Метод возвращает целое число, являющееся идентификатором задачи.
Метод clearWatch предназначен для удаления задачи по её идентификатору, которую вы создали посредством watchPosition .
Источник
Browser detection using the user agent
Serving different Web pages or services to different browsers is usually a bad idea. The Web is meant to be accessible to everyone, regardless of which browser or device they’re using. There are ways to develop your website to progressively enhance itself based on the availability of features rather than by targeting specific browsers.
But browsers and standards are not perfect, and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. This document will guide you in doing this as correctly as possible.
Note: It’s worth re-iterating: it’s very rarely a good idea to use user agent sniffing. You can almost always find a better, more broadly compatible way to solve your problem!
Considerations before using browser detection
When considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. Start by trying to identify why you want to do it.
Are you trying to work around a specific bug in some version of a browser?
Look, or ask, in specialized forums: you’re unlikely to be the first to hit this problem. Also, experts, or people with another point of view, can give you ideas for working around the bug. If the problem seems uncommon, it’s worth checking if this bug has been reported to the browser vendor via their bug tracking system (Mozilla; WebKit; Blink; Opera). Browser makers do pay attention to bug reports, and the analysis may hint about other workarounds for the bug.
Are you trying to check for the existence of a specific feature?
Your site needs to use a specific Web feature that some browsers don’t yet support, and you want to send those users to an older Web site with fewer features but that you know will work. This is the worst reason to use user agent detection because odds are eventually all the other browsers will catch up. In addition, it is not practical to test every one of the less popular browsers and test for those Web features. You should never do user agent sniffing. There is always the alternative of doing feature detection instead.
Do you want to provide different HTML depending on which browser is being used?
This is usually a bad practice, but there are some cases in which this is necessary. In these cases, you should first analyze your situation to be sure it’s really necessary. Can you prevent it by adding some non-semantic
Avoiding user agent detection
If you want to avoid using user agent detection, you have options!
Feature detection is where you don’t try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it’s not, you use a fallback. In those rare cases where behavior differs between browsers, instead of checking the user agent string, you should instead implement a test to detect how the browser implements the API and determine how to use it from that. An example of feature detection is as follows. In 2017, Chrome unflagged experimental lookbehind support in regular expressions, but no other browser supported it. So, you might have thought to do this:
The above code would have made several incorrect assumptions: First, it assumed that all user agent strings that include the substring «Chrome» are Chrome. UA strings are notoriously misleading. Then, it assumed that the lookbehind feature would always be available if the browser was Chrome. The agent might be an older version of Chrome, from before support was added, or (because the feature was experimental at the time) it could be a later version of Chrome that removed it. Most importantly, it assumed no other browsers would support the feature. Support could have been added to other browsers at any time, but this code would have continued choosing the inferior path.
Problems like these can be avoided by testing for support of the feature itself instead:
As the above code demonstrates, there is always a way to test browser support without user agent sniffing. There is never any reason to check the user agent string for this.
Lastly, the above code snippets bring about a critical issue with cross-browser coding that must always be taken into account. Don’t unintentionally use the API you are testing for in unsupported browsers. This may sound obvious and simple, but sometimes it is not. For example, in the above code snippets, using lookbehind in short-regexp notation (for example, /reg/igm) will cause a parser error in unsupported browsers. Thus, in the above example, you would use new RegExp(«(? Progressive enhancement
This design technique involves developing your Web site in ‘layers’, using a bottom-up approach, starting with a simpler layer and improving the capabilities of the site in successive layers, each using more features.
This is a top-down approach in which you build the best possible site using all the features you want, then tweak it to make it work on older browsers. This can be harder to do, and less effective, than progressive enhancement, but may be useful in some cases.
Mobile device detection
Arguably the most common use and misuse of user agent sniffing is to detect if the device is a mobile device. However, people too often overlook what they are really after. People use user agent sniffing to detect if the users’ device is touch-friendly and has a small screen so they can optimize their website accordingly. While user agent sniffing can sometimes detect these, not all devices are the same: some mobile devices have big screen sizes, some desktops have a small touchscreen, some people use smart TV’s which are an entirely different ballgame altogether, and some people can dynamically change the width and height of their screen by flipping their tablet on its side! So, user agent sniffing is definitely not the way to go. Thankfully, there are much better alternatives. Use Navigator.maxTouchPoints to detect if the user’s device has a touchscreen. Then, default back to checking the user agent screen only if (!(«maxTouchPoints» in navigator)) < /*Code here*/>. Using this information of whether the device has a touchscreen, do not change the entire layout of the website just for touch devices: you will only create more work and maintenance for yourself. Rather, add in touch conveniences such as bigger, more easily clickable buttons (you can do this using CSS by increasing the font size). Here is an example of code that increases the padding of #exampleButton to 1em on mobile devices.
As for the screen size, use window.innerWidth and window.addEventListener(«resize», function()< /*refresh screen size dependent things*/ >). What you want to do for screen size is not slash off information on smaller screens. That will only annoy people because it will force them to use the desktop version. Rather, try to have fewer columns of information in a longer page on smaller screens while having more columns with a shorter page on larger screen sizes. This effect can be easily achieved using CSS flexboxes, sometimes with floats as a partial fallback.
Also try to move less relevant/important information down to the bottom and group the page’s content together meaningfully. Although it is off-topic, perhaps the following detailed example might give you insights and ideas that persuade you to forgo user agent sniffing. Let us imagine a page composed of boxes of information; each box is about a different feline breed or canine breed. Each box has an image, an overview, and a historical funfact. The pictures are kept to a maximum reasonable size even on large screens. For the purposes of grouping the content meaningfully, all the cat boxes are separated from all the dog boxes such that the cat and dog boxes are not intermixed together. On a large screen, it saves space to have multiple columns to reduce the space wasted to the left and to the right of the pictures. The boxes can be separated into multiple columns via two equally fair method. From this point on, we shall assume that all the dog boxes are at the top of the source code, that all the cat boxes are at the bottom of the source code, and that all these boxes have the same parent element. There a single instance of a dog box immediately above a cat box, of course. The first method uses horizontal Flexboxes to group the content such that when the page is displayed to the end user, all the dogs boxes are at the top of the page and all the cat boxes are lower on the page. The second method uses a Column layout and resents all the dogs to the left and all the cats to the right. Only in this particular scenario, it is appropriate to provide no fallback for the flexboxes/multicolumns, resulting in a single column of very wide boxes on old browsers. Also consider the following. If more people visit the webpage to see the cats, then it might be a good idea to put all the cats higher in the source code than the dogs so that more people can find what they are looking for faster on smaller screens where the content collapses down to one column.
Next, always make your code dynamic. The user can flip their mobile device on its side, changing the width and height of the page. Or, there might be some weird flip-phone-like device thing in the future where flipping it out extends the screen. Do not be the developer having a headache over how to deal with the flip-phone-like device thing. Never be satisfied with your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. The simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. If there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. Also note that there is a huge difference between the media queries (max-width: 25em) , not all and (min-width: 25em) , and (max-width: 24.99em) : (max-width: 25em) excludes (max-width: 25em) , whereas not all and (min-width: 25em) includes (max-width: 25em) . (max-width: 24.99em) is a poor man’s version of not all and (min-width: 25em) : do not use (max-width: 24.99em) because the layout might break on very high font sizes on very high definition devices in the future. Always be very deliberate about choosing the right media query and choosing the right >=, , or Firefox/xyz
[1] Safari gives two version numbers: one technical in the Safari/xyz token, and one user-friendly in a Version/xyz token.
Of course, there is absolutely no guarantee that another browser will not hijack some of these things (like Chrome hijacked the Safari string in the past). That’s why browser detection using the user agent string is unreliable and should be done only with the check of the version number (hijacking of past versions is less likely).
Browser version
The browser version is often, but not always, put in the value part of the BrowserName/VersionNumber token in the User Agent String. This is of course not the case for Internet Explorer (which puts the version number right after the MSIE token), and for Opera after version 10, which has added a Version/VersionNumber token.
Here again, be sure to take the right token for the browser you are looking for, as there is no guarantee that others will contain a valid number.
Rendering engine
As seen earlier, in most cases, looking for the rendering engine is a better way to go. This will help to not exclude lesser known browsers. Browsers sharing a common rendering engine will display a page in the same way: it is often a fair assumption that what will work in one will work in the other.
There are five major rendering engines: Trident, Gecko, Presto, Blink, and WebKit. As sniffing the rendering engines names is common, a lot of user agents added other rendering names to trigger detection. It is therefore important to pay attention not to trigger false-positives when detecting the rendering engine.
Engine | Must contain | Comment |
---|---|---|
Gecko | Gecko/xyz | |
WebKit | AppleWebKit/xyz | Pay attention, WebKit browsers add a ‘like Gecko’ string that may trigger false positive for Gecko if the detection is not careful. |
Presto | Opera/xyz | Note: Presto is no longer used in Opera browser builds >= version 15 (see ‘Blink’) |
Trident | Trident/xyz | Internet Explorer put this token in the comment part of the User Agent String |
EdgeHTML | Edge/xyz | The non-Chromium Edge puts its engine version after the Edge/ token, not the application version. Note: EdgeHTML is no longer used in Edge browser builds >= version 79 (see ‘Blink’). |
Blink | Chrome/xyz |
Rendering engine version
Most rendering engines put the version number in the RenderingEngine/VersionNumber token, with the notable exception of Gecko. Gecko puts the Gecko version number in the comment part of the User Agent after the rv: string. From Gecko 14 for the mobile version and Gecko 17 for the desktop version, it also puts this value in the Gecko/version token (previous version put there the build date, then a fixed date called the GeckoTrail).
The Operating System is given in most User Agent strings (although not web-focused platforms like Firefox OS), but the format varies a lot. It is a fixed string between two semi-colons, in the comment part of the User Agent. These strings are specific for each browser. They indicate the OS, but also often its version and information on the relying hardware (32 or 64 bits, or Intel/PPC for Mac).
Like in all cases, these strings may change in the future, one should use them only in conjunction with the detection of already released browsers. A technological survey must be in place to adapt the script when new browser versions are coming out.
Mobile, Tablet or Desktop
The most common reason to perform user agent sniffing is to determine which type of device the browser runs on. The goal is to serve different HTML to different device types.
- Never assume that a browser or a rendering engine only runs on one type of device. Especially don’t make different defaults for different browsers or rendering engines.
- Never use the OS token to define if a browser is on mobile, tablet or desktop. The OS may run on more than one type of (for example, Android runs on tablets as well as phones).
The following table summarizes the way common browser vendors indicate that their browsers are running on a mobile device:
Browser | Rule | Example |
---|---|---|
Mozilla (Gecko, Firefox) | Mobile or Tablet inside the comment. | Mozilla/5.0 (Android; Mobile; rv:13.0) Gecko/13.0 Firefox/13.0 |
WebKit-based (Android, Safari) | Mobile Safari token outside the comment. | Mozilla/5.0 (Linux; U; Android 4.0.3; de-ch; HTC Sensation Build/IML74K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30 |
Blink-based (Chromium, Google Chrome, Opera 15+, Edge on Android) | Mobile Safari token outside the comment. | Mozilla/5.0 (Linux; Android 4.4.2); Nexus 5 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Mobile Safari/537.36 OPR/20.0.1396.72047 |
Presto-based (Opera 12-) | Opera Mobi/xyz token inside the comment. | Opera/9.80 (Android 2.3.3; Linux; Opera Mobi/ADR-1111101157; U; es-ES) Presto/2.9.201 Version/11.50 |
Internet Explorer | IEMobile/xyz token in the comment. | Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0) |
Edge on Windows 10 Mobile | Mobile/xyz and Edge/ tokens outside the comment. | Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Xbox; Xbox One) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Mobile Safari/537.36 Edge/16.16299 |
In summary, we recommend looking for the string Mobi anywhere in the User Agent to detect a mobile device.
Note: If the device is large enough that it’s not marked with Mobi , you should serve your desktop site (which, as a best practice, should support touch input anyway, as more desktop machines are appearing with touchscreens).
Источник