PROWAREtech

articles » current » javascript » check-for-mobile-device

JavaScript: Check for Mobile Device

How to determine if the browser is on a mobile device like Apple iPhone, Apple iPod, Google Android or Apple iPad including the iPad Pro with iPadOS version 15.x and 16.x or later.

Mobile devices have limited resources so here is a good way to check if a web application is running on a mobile device and then use it to modify the application to react differently based on the platform.

Since iPadOS version 15, the Safari User Agent on the iPad Pro reports as being on the desktop, so always check the navigator.maxTouchPoints to know if it is a tablet or not.


var isMobileDevice = (function () {
	var ua = navigator.userAgent;
	var p = navigator.platform;
	var iphone = ua.indexOf("iPhone") > -1;
	var ipod = ua.indexOf("iPod") > -1;
	var ipad = ua.indexOf("iPad") > -1;
	var android = /Android (\d+(?:\.\d+)*)/.test(ua);
	if (/iPad|iPhone|iPod/.test(p) | (iphone | ipad | ipod | android)) {
		return true;
	}
	else {
		return navigator.maxTouchPoints && navigator.maxTouchPoints > 2 && /MacIntel/.test(p);
	}
})();

Example usage (click the JS icon to run):


var isMobileDevice = (function () {
	var ua = navigator.userAgent;
	var p = navigator.platform;
	var iphone = ua.indexOf("iPhone") > -1;
	var ipod = ua.indexOf("iPod") > -1;
	var ipad = ua.indexOf("iPad") > -1;
	var android = /Android (\d+(?:\.\d+)*)/.test(ua);
	if (/iPad|iPhone|iPod/.test(p) | (iphone | ipad | ipod | android)) {
		return true;
	}
	else {
		return navigator.maxTouchPoints && navigator.maxTouchPoints > 2 && /MacIntel/.test(p);
	}
})();
alert(isMobileDevice ? "This is a mobile device!" : "This is not a mobile device.");

Here is another example that returns more information about the device:


var MobileDevice = (function () {
	var ua = navigator.userAgent;
	var p = navigator.platform;
	var iphone = /iPhone/.test(p) || ua.indexOf("iPhone") > -1;
	var ipod = /iPod/.test(p) || ua.indexOf("iPod") > -1;
	var ipad = /iPad/.test(p) || ua.indexOf("iPad") > -1;
	var ipadpro = (function () {
		if (ipad) {
			return false;
		}
		else {
			return (navigator.maxTouchPoints && navigator.maxTouchPoints > 2 && /MacIntel/.test(p)) != 0;
		}
	})();
	var android = /Android (\d+(?:\.\d+)*)/.test(ua);
	var ismobile = (iphone | ipad | ipadpro | ipod | android) != 0;
	return { Enabled: ismobile, iPhone: iphone, iPod: ipod, iPad: (ipad | ipadpro) != 0, iPadPro: ipadpro, Android: android };
})();

alert(MobileDevice.Enabled ? "This is a mobile device!" : "This is not a mobile device.");
alert((function () {
	var str = "";
	for (var m in MobileDevice) {
		str += "MobileDevice." + m + "=" + MobileDevice[m] + "\r\n";
	}
	return str;
})());

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE