Javascript операционная система пользователя

How To Detect Mobile Device, OS using JavaScript

Hello Devs, In this blog, we are going to learn that how you can detect mobile device or browser or OS using JavaScript and you can redirect the user to the mobile application or to the web application automatically.

Table of content

So without wasting any time, lets get into the tutorial.

1.What is navigator object in JavaScript

To get the bowser details or device details, JavaScript stores these information in the navigator property of window object.
navigator object contains lots of information about the browser, some of the most used/ important information we will see later in this tutorial.

Lets first see what navigator object is.
if you directly want to see how to get the detect mobile and desktop then you can skip this part can click here

navigator object contains information about the browser.
(NOTE: Not all but all major browser support this object)

2.Some of the most important properties are,

  1. Clipboard — used to copy something to clipboard and paste it any where (Ex. while making Click to copy)
  2. connection
  3. language — shows the language of browser.
  4. geolocation — Returns a Geolocation object that can be used to locate the user’s position
  5. onLine — check whether the browser is online
  6. platform — machine type where browser is installed.
  7. cookieEnabled — it returns a Boolean value that indicates whether cookies are enabled or not.
  8. serviceWorker — mainly used to checks if the browser supports service workers
  9. vibrate(time) — make device vibrate if it support that
  10. userAgent — will see below
  11. userAgentData — will see below

I think this much information about the navigator object is enough to understand what is navigator object and what all information it contains

3.How to detect mobile device or browser or OS.

To get these information we will use the property userAgent , userAgentData of navigator object.

navigator.userAgent
userAgent will give you the information of lot of things like device name, browser name, OS version but the information returned by browser is not much understandable.
So, we can understand these returned information from the hack.

to get OS version and name you can follow the below hack,

if (window.navigator.userAgent.indexOf("Windows NT 10.0")!= -1) console.log("OS is Windows 10");> if (window.navigator.userAgent.indexOf("Windows NT 6.3") != -1) console.log("OS is Windows 8.1");> if (window.navigator.userAgent.indexOf("Windows NT 6.2") != -1) console.log("OS is Windows 8");> if (window.navigator.userAgent.indexOf("Windows NT 6.1") != -1) console.log("OS is Windows 7");> if (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1) console.log("OS is Windows Vista");> if (window.navigator.userAgent.indexOf("Windows NT 5.1") != -1) console.log("OS is Windows XP");> if (window.navigator.userAgent.indexOf("Windows NT 5.0") != -1) console.log("OS is Windows 2000");> if (window.navigator.userAgent.indexOf("Mac") != -1) console.log("OS is Mac/iOS");> if (window.navigator.userAgent.indexOf("X11") != -1) console.log("OS is UNIX");> if (window.navigator.userAgent.indexOf("Linux")!= -1) console.log("OS is Linux");> 

to check mobile device info you can follow below hack,

 function detectMobile()  const toMatch = [ /Android/i, /webOS/i, /iPhone/i, /iPad/i, /iPod/i, /BlackBerry/i, /Windows Phone/i ]; return toMatch.some((toMatchItem) =>  return navigator.userAgent.match(toMatchItem); >); > 

userAgent is much more complex to get these details.
So we have one more property i.e.
navigator.userAgentData
This gives the information about browser and mobile detection in 1 line.

navigator.userAgentData.mobile; //returns true or false, depending on the condition 

NOTE: Both of these 2 ways are not recommended to be use in the production.

So lets now see the best way to do so,

4.Better way is,

using matchMedia
it gives you more flexibility to decide that after what screen size you want to deal it as mobile or desktop and lot of other info,
please check official doc from MDN, MDN — Media Query
MDN- Media Query Features
About Pointer

function DetectDevice()  let isMobile = window.matchMedia || window.msMatchMedia; if(isMobile)  let match_mobile = isMobile("(pointer:coarse)"); return match_mobile.matches; > return false; > DetectDevice() //return true if mobile, and return false if desktop 

matchMedia also gives you the right to let you choose that after what screen-size you want to treat the device as Mobile(same as CSS Media Query) and its much more flexible than navigator object.

if (window.matchMedia("only screen and (max-width: 760px)"))  //do something you want to for the screen size less than 760 > 

we can also use window and screen object achieve this, but these are the older way and much complicated in bigger applications.

if(window.innerWidth > 768)//do something> if(screen.width > 768)//do something> 

Thank you for reading this far. This is a brief introduction on How to Detect Mobile Screen & OS using JavaScript .
If you find this article useful, like and share this article. Someone could find it useful too.

If you find anything technically inaccurate please feel free to comment below.

Источник

Get OS details from the webpage in JavaScript. 👷‍♂️

The other day I was making a random demo app in Vue where I wanted to get the user’s machine information (not for snooping) but to display the basic information like the Operating System (OS) name with version etc. I had to confess I was so bad at this that I almost immediately revoked the idea to do such a thing. But now I think if not on Vue, I need to do this with vanilla JS. Taking this move further, I decided to dynamically add or delete DOM elements after detecting the OS. Though not this, we’ll definitely learn how to detect the OS on both web and mobile.

Detecting desktop OS (Windows/Mac/Linux)

First, let’s detect whether the client’s machine is running an OS that seriously needs to ramp up its application store (Windows) or the one which almost all programmers and hackers love the most (Linux) or the OS which can exclusively run XCode (Mac). This can simply be achieved by analyzing the value of navigator.appVersion of the window object. This one simple thing can do many things. Not only it will tell you about the current device OS (we’ll see more about this below), but also, it can be used to get the version information about the browser it’s currently running on. Let’s declare detectedOS as a variable in JS which holds the String information regarding the OS type. Next, we’ll make three if checks ( switch can work too).

// default value just in case if nothing is detected var detectedOS = "Unknown OS"; 

Inside the first check, let’s use the navigator.appVersion to get the index of the three major OS platforms: Win (Windows), Mac (MacOS), and Linux .

if (navigator.appVersion.indexOf("Mac") != -1) detectedOS = "MacOS"; 

Here, we check if the index value is not equal to 1 , then we set our variable value to «MacOS». Similarly, we can perform the same check for the other two OS:

var detectedOS = "Unknown OS"; if (navigator.appVersion.indexOf("Mac") != -1) detectedOS = "MacOS"; if (navigator.appVersion.indexOf("Win") != -1) detectedOS = "Windows"; if (navigator.appVersion.indexOf("Linux") != -1) detectedOS = "Linux"; 

Okay, all cool but how to display the user that a specific OS has been detected? There are multiple ways to do this. One good way would be: Adding an alert() which says «Device OS is: » when a button is clicked.

var detectOS = "Unknown OS"; if (navigator.appVersion.indexOf("Win") != -1) detectOS = "Windows"; if (navigator.appVersion.indexOf("Mac") != -1) detectOS = "MacOS"; if (navigator.appVersion.indexOf("Linux") != -1) detectOS = "Linux"; document.querySelector('button').addEventListener('click', detect); function detect()  alert(`Device OS is: $detectOS>`) > 

This is how it looks on Mac: Detection on Mac On Windows: Detection on Windows And on Linux: 404 image

Detecting mobile OS (Android/iOS)

Android demo 1

With the current code, if you try to run it on mobile (via CodePen), you’ll see the following alert: While it’s true that Android is based on a modified version of Linux, it’s not entirely a Linux OS. So how do we make sure that «Android» is detected here instead of «Linux»? This is explained by a Stackoverflow user Vladyslav Turak in the following answer:

I learnt a lot about window.navigator object and its properties: platform , appVersion and userAgent . To my mind, it’s almost impossible to detect user’s OS with 100% sure, but in my case 85%-90% was enough for me. So, after examining tons of the stackoverflows’ answers and some articles, I…

function getOS()  var userAgent = window.navigator.userAgent, platform = window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod'], os = null; if (macosPlatforms.indexOf(platform) !== -1)  os = 'Mac OS'; > else if (iosPlatforms.indexOf(platform) !== -1)  os = 'iOS'; > else if (windowsPlatforms.indexOf(platform) !== -1)  os = 'Windows'; > else if (/Android/.test(userAgent))  os = 'Android'; > else if (!os && /Linux/.test(platform))  os = 'Linux'; > return os; > alert(getOS()); 

Android demo

As you can see, we are using the same if statement checks as before, but for Android, we are testing /Android/.test with the navigator.userAgent . This is quite a nice workaround and upon running it on my Android phone, here is the result: I don’t have an iOS device to check for that device. You can do so and let me know below in the comments. Note that the guy who gave the answer to this has clearly stated that:

This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can’t guarantee 100% sure.

Источник

Javascript операционная система пользователя

В данном посте хочу поделится с Вами одним из способов определения платформы на JavaScript пользователя, который перешел на ваш ресурс. Определить версию и тип браузера проще всего при помощи JavaScript. JavaScript имеет стандартный объект под названием navigator, который содержит данные о браузере пользователя.

Для начала мы создадим массив объектов устройств с их платформой.

После нам необходимо написать функцию, которая будет определять свойства пользователя перешедшего на наш сайт. Тут нам поможет navigator. Объект navigator имеет много свойств, но в данном случае нас интересует свойство. UserAgent — это строка содержит данные о браузере, операционной системы, и многое другое.

 var userDeviceArray = [ , , , , , , , , ]; var platform = navigator.userAgent; function getPlatform() < for (var i in userDeviceArray) < if (userDeviceArray[i].platform.test(platform)) < return userDeviceArray[i].device; >> return 'Неизвестная платформа!' + platform; > console.log('Ваша платформа: ' + getPlatform()); 

В функции getPlatform(), мы пробегаем по массиву userDeviceArray цыклом и проверяем условием имеется ли в нашем массиве та платформа, которую нам определил navigator.userAgent.

ПРИМЕЧАНИЕ. Определение типа браузера при помощи JavaScript не является надежным. JavaScript может быть отключен пользователем или userAgent может быть подменен.

Источник

Читайте также:  !DOCTYPE
Оцените статью