ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.

Follow publication

Member-only story

Essential JavaScript Functions for Detecting User’s Device Characteristics

David Dal Busco
ITNEXT
Published in
4 min readNov 12, 2023

--

Photo by Bram Naus on Unsplash

Time and again, I’ve encountered the need to implement features in my web-based projects that specifically target certain types of devices. Each time, I find myself falling back on the same set of utilities I’ve been using for years. It’s high time I shared these invaluable tools in a blog post.

In this article, you’ll gain access to a curated collection of JavaScript functions for identifying iOS and Android devices, detecting fullscreen mode, distinguishing Firefox from Safari, and more.

It’s important to be aware that some of these methods are based on parsing the navigator user-agent string, which might see changes in the future as Google plans to reduce the information provided by this string.

isMobile

Let’s start with the detection of a mobile device. I determine if a user is using my applications in a browser-based environment that might be a mobile device by testing whether the user is using a pointing device with limited accuracy, such as a touch screen, and which is not a precise device such as a mouse.

const isMobile = (): boolean => {
const isTouchScreen = window.matchMedia('(any-pointer:coarse)').matches;
const isMouseScreen = window.matchMedia('(any-pointer:fine)').matches;

return isTouchScreen && !isMouseScreen;
};

The matchMedia interface returns an object that can be used to determine if the document or web page matches a specific media query. To test the pointing device, I utilize the any-pointer CSS media feature.

isIPad

Identifying an iPad device involves inspecting the user-agent, but it also necessitates combining this data with the previous mobile detection function. This is because Safari presents a string similar to that of desktop or laptop devices.

const isIPad = (): boolean => {
const {
navigator: { userAgent }
} = window;

// iOS 12 and below
if (/iPad/i.test(userAgent)) {
return true;
}

// iOS 13+
return /Macintosh/i.test(userAgent) && isMobile();
};

--

--

Published in ITNEXT

ITNEXT is a platform for IT developers & software engineers to share knowledge, connect, collaborate, learn and experience next-gen technologies.