Detect MacOS, iOS, Windows, Android and Linux OS with JS [duplicate] - javascript

This question already has answers here:
How to detect my browser version and operating system using JavaScript?
(11 answers)
Closed 6 years ago.
How to detect MacOS X, iOS, Windows, Android and Linux operating system with JavaScript?

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 wrote something like this:
function getOS() {
var userAgent = window.navigator.userAgent,
platform = window.navigator?.userAgentData?.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 (/Linux/.test(platform)) {
os = 'Linux';
}
return os;
}
alert(getOS());
Inspiration:
What is the list of possible values for navigator.platform as of today?
Best way to detect Mac OS X or Windows computers with JavaScript or jQuery
How to detect my browser version and operating system using JavaScript?
How to detect Browser and Operating System Name and Version using javaScript
Also I used the lists of mobile and desktop browsers to test my code:
List of all Mobile Browsers
List of all Browsers
This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.

Related

how to hide/show a React component depending on device browser?

Looking to hide/show a component in a React/Nextjs/tailwind webapp depending on the device that the user is on (e.g. desktop vs tablet vs mobile) since there are certain keys on the keyboard available for desktop but not on table and mobile (e.g. the tab key). Don't want to do it by screen size since this is a device problem (no tab on keyboard) rather than a screen size problem
Initially I thought about getting device type (code referenced from another stackoverflow Q/A), but this seems to fail when the user is on a device such as an ipad and is using the Desktop version for that browser (e.g. Desktop safari and not mobile safari). Is there a better way to handle this such that it can properly check what device the user is on in order to be able to hide/show the react component?
const getDeviceType = () => {
const ua = navigator.userAgent;
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
return "tablet";
}
if (
/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
ua
)
) {
return "mobile";
}
return "desktop";
};
In JavaScript you can detect browser with JavaScript using window.navigator
Code example according to https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator would be
var sBrowser, sUsrAg =
navigator.userAgent;
// The order matters here, and this may
report false positives for unlisted
browsers.
if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox";
// "Mozilla/5.0 (X11; Ubuntu; Linux
x86_64; rv:61.0) Gecko/20100101
Firefox/61.0"
}
alert("You are using: " + sBrowser);
But for react there's another package you can use that is npm install react-device-detect
Code example would be
import { browserName, browserVersion }
from "react-device-detect"
console.log(`${browserName}
${browserVersion}`);
After detecting browser you just conditionally render whatever you want to show

How to detect iPad Pro as iPad using javascript?

We were able to detect an iPad device using javascript like this:
function isDeviceiPad(){
return navigator.platform.match(/iPad/i);
}
That worked perfectly in detecting iPad devices, but when we checked from an iPad Pro (10.5 inch), it does not detect that it is an iPad.
To further investigate, we drilled down into the navigator object, checked both platform and userAgent, and got these results:
navigator.platform = 'MacIntel';
navigator.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)
AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Safari/605.1.15)';
The issue is that navigator.platform = 'MacIntel' (which is the same as the MacBook Pro) is returned instead of the iPad. We need a way to detect that this is an iPad and not a MacBook Pro, but it seems that the navigator does not return iPad like it does with older iPads.
Any idea how we can fix this issue?
iPadPro reports navigator.platform the browser as 'MacIntel', but that is the same as other platforms.
Currently (2019) difference between iPadPro and the other platforms is that iPadPro is touch enabled.
Here are a couple of helpful methods.
function isIOS() {
if (/iPad|iPhone|iPod/.test(navigator.platform)) {
return true;
} else {
return navigator.maxTouchPoints &&
navigator.maxTouchPoints > 2 &&
/MacIntel/.test(navigator.platform);
}
}
function isIpadOS() {
return navigator.maxTouchPoints &&
navigator.maxTouchPoints > 2 &&
/MacIntel/.test(navigator.platform);
}
I guess that iPad Pro is upgraded to iPadOS 13 Beta. Since Apple claimed Desktop-Class Browsing with Safari on iPadOS, it seems mobile Safari also mimics macOS behavior and user agent.
So, the short answer is it's not possible.
However you can try workarounds from answers to this question.
Currently, in October 2020 the only way I know is:
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 0) || navigator.platform === 'iPad'
You can use Regular Expression for this.
var isIPadPro = /Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;
You may use screen size to check it, iPad pro came with 2 different side.
Detail implement bellow, modify it as your use case
function isIpadPro() {
var ratio = window.devicePixelRatio || 1;
var screen = {
width : window.screen.width * ratio,
height : window.screen.height * ratio
};
return (screen.width === 2048 && screen.height === 2732) || (screen.width === 2732 && screen.height === 2048) || (screen.width === 1536 && screen.height === 2048) || (screen.width === 2048 && screen.height === 1536);
}
Screen size reference: http://screensiz.es/
The most easiest way to detect an "iPad Pro 10.5" device is through checking its screen size which is "window.screen.height x window.screen.width = 1112 x 834"
However, I am wondering why you need to detect the device model. In case you want to detect mobile browsers, take a look at this question: Detecting Mobile Browser
You should be able to use the screen size to distinguish them. Thought you will need to find the real value for each iPad pro you want to detect.
window.screen.height
window.screen.width
Capacitor has a useful web plugin to get device info (https://capacitor.ionicframework.com/docs/apis/device#example).
It does not differentiate between iPad Pro and regular iPad, but then you could combine the use of this plugin with the screen size solutions proposed.
If you'd like to do this yourself, you can take a look at the code here: https://github.com/ionic-team/capacitor/blob/master/core/src/web/device.ts
It is possible.
You can use this function.
This will also check a mac with a touch device (iPad 13).
<script type="text/javascript">
if(iOS()){
alert('iOS');
}
function iOS() {
return [
'iPad Simulator',
'iPhone Simulator',
'iPod Simulator',
'iPad',
'iPhone',
'iPod'
].includes(navigator.platform)
// iPad on iOS 13 detection
||
(navigator.userAgent.includes("Mac") && "ontouchend" in document)
}
</script>

Detect if the user is navigating through the safari mobile browser on iphone

I am trying to detect if the user is navigating my website from safari browser on the iphone using jquery / javascript.
I am able to detect the IOS Environment using the user agent string
/iphone/i.test(navigator.userAgent.toLowerCase())
But this detects the Apple Webkit Environment i.e. it is same for all the browsers on the device. Can anyone suggest any different approach.
UPDATED:
Try this, for detecting Safari browser in an iPhone:
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
It identifies Safari 3.0+ and distinguishes it from Chrome.
JsFiddle
Since the other answer doesn't include detection of an iPhone, including that part.
var isIphone = /(iPhone)/i.test(navigator.userAgent);
var isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/);
if(isIphone && isSafari){
//do something
}
If you want to detect a particular iOS version and above, say iOS 7.0 and above then you can use the below code. It detects iOS version 7-19(for upcoming versions).
var isIphone= /(iPhone)*(OS ([7-9]|1[0-9])_)/i.test(navigator.userAgent);
var isFirefox = navigator.userAgent.indexOf("FxiOS") != -1;
var isChrome = navigator.userAgent.indexOf("CriOS") != -1;
var isEdge = navigator.userAgent.indexOf("EdgiOS") != -1;
var isOpera = navigator.userAgent.indexOf("OPT") != -1;
if (!isFirefox && !isChrome && !isEdge && !isOpera){
console.log("Only display in Safari")
} else {
console.log("Only display in Firefox/Chrome/Edge/Opera")
}
Hi, this way worked for me to detect only safari in ios mobile. The value FxiOs, CriOs, etc, I get from the userAgent value.

Version Number of Smartphone OS's [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to programmatically get iOS’s alphanumeric version string
Is there any future proof regex to get the version number of the following smartphone OS's from the user-agent?
Android
(I have found something like: /Androids+([d.]+)/ )
iOS
BlackBerry
Any advise would be much appreciated.
Clarification: Seems like the question is asking how to get the mobile device OS version in a web-app, probably using JS.
UPDATE:
After I got quite bashed to ask this question I want at least provide the solution I came up with:
supportedDevice: function() {
var supportedDevice = false;
var userAgent = window.navigator.userAgent;
// check for supported Android device
if ( /Android/.test(userAgent) ) {
var a_index = Number(userAgent.indexOf('Android')) + 8;
var a_version = +userAgent.substring(a_index, a_index+1);
if ( a_version >= 3 ) {
supportedDevice = true;
console.log('Android device supported!')
}
}
// check for iOS supported devices
else if ( /iPhone/.test(userAgent) ) {
var i_index = Number(userAgent.indexOf('iPhone OS')) + 10;
var i_version = +userAgent.substring(i_index, i_index+1);
if ( i_version >= 6 ) {
supportedDevice = true;
console.log('iPhone device supported!')
}
}
// check for iOS supported devices
else if ( /BlackBerry/.test(userAgent) ) {
var b_index = Number(userAgent.indexOf('Version/')) + 8;
var b_version = +userAgent.substring(b_index, b_index+1);
if ( b_version >= 6 ) {
supportedDevice = true;
console.log('BB device supported!')
}
}
return supportedDevice;
}
If you need to obtain the version number in a web app, your best bet would be to use the device User Agent and parse out the version number. A more robust method would be to look up the user agent in the WURFL database to obtain the device characteristics and the corresponding OS. The first method is simpler.
If you are using an app, most OS SDKs provide APIs to identify the version of the OS running on the device

What's the best way to detect a webOS tablet with jQuery / plain JS

I'm looking for the best way to detect a webOS tablet using plain JS and if it's any easier also using jQuery. The user agent of the tablet should look something like this:
User-Agent:Mozilla/5.0 (webOS/1.3; U; en-US) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Desktop/1.0
So an easy way would be:
var deviceAgent = navigator.userAgent.toLowerCase();
webOS = deviceAgent.match(/(webos)/);
Is that the best way to do it already? You're likely going to say detect the feature you need to make certain is present but that won't work for me because the feature I want is present but not working as it would on any desktop, so I really just want to know is this a webOS device or not.
Update: Just found that the tablet really uses another user agent:
Mozilla/5.0 (hp-tablet; Linux; hpwOS/3.0.0; U; xx-xx) AppleWebKit/534.6 (KHTML, like Gecko) wOSBrowser/233.48 Safari/534.6 TouchPad/1.0
So the above should probably rather be:
var deviceAgent = navigator.userAgent.toLowerCase();
webOS = deviceAgent.match(/(webos|hpwos)/);
Here's a function in PHP that will detect WebOS and any other mobile device you could need. Less than 1kb in code =)
function detectMobileDevice() {
if(preg_match('/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i', $_SERVER['HTTP_USER_AGENT'])) {
return true;
}
else {
return false;
}
}
if you want to do ONLY webOS, change line 2 to:
if(preg_match('/(webos)/i', $_SERVER['HTTP_USER_AGENT'])) {
to use:
if(detectMobileDevice()) {
// If mobile device detected, do something
}
else {
// Otherwise, do something else...
}
if you need more details, visit here: http://www.justindocanto.com/scripts/detect-a-mobile-device-in-php-using-detectmobiledevice
I don't know if you can do any feature detection that'll only identify WebOS. It's WebKit-based, so all other WebKit-based platforms will have the same features. Looking at Zepto.js' source, they're doing exactly the same as you are:
ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/)
(The 2nd capture is the version)
From detect.js

Categories

Resources