Ways to identify a mobile device

My website uses Javascript to detect when someone is accessing it from a mobile device. This detection method was effective until Apple updated their iPad OS from IOS 13.1 to iPadOS 13.1.

The code I use for detection is as follows:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) 
{ 

//      alert('This is a mobile device');
    }

This code worked fine on devices running IOS 13.1, with the navigator.userAgent showing this:

Mozilla/5.0 (iPad; CPU OS 12_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.2 Mobile/15E148 Safari/604.1

However, after the update to iPadOS 13.1, the user agent now appears as:

Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.1 Safari/605.1.15

This new user agent string is similar to that of an Apple Mac, making it difficult to distinguish between mobile and desktop devices based on user agent alone.

While checking screen size could be a solution, the wide variety of mobile devices makes this method less reliable. Does anyone have any suggestions on how to address this issue?

Answer №1

When it comes to distinguishing between different devices in Javascript, I prefer using feature detection such as touch capability and screen size media queries. This combination helps ensure reliability when identifying phones versus larger screens like desktops or tablets. The touchscreen detection method I utilize is sourced from an informative article on mdn.

export const isMobile = () => {
   let hasTouchScreen = false;
   if ("maxTouchPoints" in navigator) {
       hasTouchScreen = navigator.maxTouchPoints > 0;
   } else if ("msMaxTouchPoints" in navigator) {
       hasTouchScreen = navigator.msMaxTouchPoints > 0;
   } else {
       let mQ = window.matchMedia && matchMedia("(pointer:coarse)");
       if (mQ && mQ.media === "(pointer:coarse)") {
          hasTouchScreen = !!mQ.matches;
       } else if ('orientation' in window) {
          hasTouchScreen = true;
       } else {
          let UA = navigator.userAgent;
          hasTouchScreen = (
              /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
              /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
          );
       }
   }
   let mQ2 = window.matchMedia && matchMedia("(max-width: 767px), (max-height: 767px)");
    return ((hasTouchScreen === true) && (mQ2.matches === true));
}

The usage of window.matchMedia is well-documented on Mozilla Developer Network. The dual queries with the comma operator serve as a logical OR condition, ensuring that mQ2 evaluates to true whenever either dimension is below 768px.

Answer №2

This function I stumbled upon seems to do the job quite nicely

function checkIfMobile() {
    return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
}; 

source:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for distinguishing between elements in React

I am facing an issue with zooming images on mouse hover using CSS. I have a code snippet that works well, but it zooms both images simultaneously. How can I differentiate between mouse movements over different elements in ReactJS? Here is the code: .styl ...

Is there a way to retract a QDate selection?

I am currently using Quasar within a Vue2.JS project. I have implemented a QDate component connected to a QPopupEdit, which includes buttons for canceling and setting the date. I am looking to trigger a specific function when the "set" button is clicked. I ...

Enhancing connections in a MongoDB database

Can someone assist me with implementing the update function in the assignmentsController? I want users to create an assignment and then be able to add a quiz to it. After updating the assignment quiz section, here is an example of what I expect as a return ...

Is your server failing to respond to requests once there are too many within a session?

A web application I developed uses frequent $.ajax() calls to send and receive data between a virtual machine host and client. However, I have encountered a recurring issue where the connection cuts out after a certain number of consecutive calls within a ...

Display larger images dynamically by hovering over thumbnails using PHP

Is there a way to display an image when I hover over a thumbnail using PHP, similar to the functionality on this website? I'm looking for a solution to implement this feature. ...

Sorting an array of elements in JavaScript based on their value relationships

I need help grouping the elements of an array based on their inner array groupings Input: const arr = [ [123, 243], [123, 435], [736, 987], [987, 774], [123, 666], [774, 999], [098, 980], ]; Output: Result = [[123, 243, 435, 666],[736, ...

The functionality for selecting text in multiple dropdown menus using the .on method is currently limited to the first dropdown

Having trouble selecting an li element from a Bootstrap dropdown and displaying it in the dropdown box? I'm facing an issue where only the text from the first dropdown changes and the event for the second dropdown doesn't work. <div class="dr ...

Exploring the process of performing an AJAX JQuery HTTP request using JavaScript and PHP on the server side - any tips?

Greetings! I have developed a web application using HTML, CSS, and JavaScript. To enhance functionality, I have integrated Bootstrap and jQuery into the project. The application comprises both client-side and server-side components. Let's take a look ...

In what way can a property in JavaScript alter an object?

I am a newcomer to node.js, although I have been writing Javascript for many years. Recently, I encountered an interesting pattern that has left me puzzled: a Flag that is used to set a modifier on the object. For example, in the socket.io documentation: ...

Leveraging React Router v5 along with Code Splitting and Server Side Rendering for optimized Data Prefetching

For a current project, I am using react-router v3 specifically for server-side rendering with data prefetching. The most efficient way to achieve this is by maintaining a centralized route configuration in either an object or an array, and iterating throug ...

Issue with history.go(-1) method malfunctioning on dropdown menu

Currently, I am facing an issue with the functionality of my back button using history.go(-1) in conjunction with a dropdown selection. Despite the source code displaying the original selected value, the UI is showing a previous value. When clicking on t ...

Having trouble with Javascript/ajax/php: data is successfully sent from server to client, but client to server communication is not working as

Apologies for the duplicate post (Admins, kindly remove the other one!). I've been receiving great assistance from you all and was hoping to seek your help once again with the following question: I am currently working on implementing AJAX by allowin ...

Utilizing ProtractorJS to Extract Numbers from Text within an Element and Dynamically Adding it to an Xpath Expression

Situation My objective is to extract text from an element on a webpage, convert that extracted text into a number in string format, and then use it for an xpath query. The code snippet below illustrates this process: var bookingRefString = element(by.css ...

Unique Dropdown Menu Design with Creative Styling

Currently, I am in the process of developing a small project that requires the use of a drop-down list. During my research, I came across a visually appealing drop-down list that did not have default styling applied to it. I am interested in learning how ...

How come the callback in Jquery fadeOut keeps looping repeatedly, and what can I do to stop this from happening?

My approach involves fading out a div box and implementing a callback function as shown below: function closeWindow(windowIdPrefix, speed) { $("#" + windowIdPrefix + "_ViewPanel").fadeOut(speed, function() { resetWindow(windowIdPre ...

Having trouble retrieving text from the data attribute

I have a Bootstrap Table with an edit button on each row. I've implemented a data formatter to include the record ID as a data attribute that should be accessible when the button is clicked. Oddly, while inspecting the element in the console shows tha ...

While working on my Laravel and Vue.js project, I encountered the following error message: "Module not found: Error: Can't resolve './vue/app' in 'C:vue odolist esourcesjs'"

Running into an issue where the app.vue file cannot be found in the app.js. I'm using Laravel version "8.31.0" and VueJS version "^2.6.12". Any assistance would be highly appreciated. The content of app.js is: require('./bootstrap'); impor ...

Is there a way to incorporate personalized image placeholders into Next.js?

The Image component has properties called placeholder and blurDataURL. The placeholder property can have a value of either 'blur' or 'empty', with no other option. I tried setting the placeholder to 'blur' and specifying the b ...

Trouble arises when emitting events in Vue using eventHub

In the development of my component, there arises a need to emit an event at a specific point in its lifecycle. This emitted event is intended to be listened to by another sibling component. To facilitate this communication, I am utilizing an event hub. H ...

Guide on incorporating geolib into React Native for distance calculation of two locations

Is there a simple way to calculate the distance between Longitude and Latitude in react native? I have the coordinates of my current location and destination, but keep encountering errors when attempting to use geolib for this calculation. I attempted to ...