0
0
JavascriptHow-ToBeginner · 3 min read

How to Detect Mobile Browser in JavaScript Easily

You can detect a mobile browser in JavaScript by checking the navigator.userAgent string for keywords like 'Mobi'. This simple check helps identify most mobile devices quickly with navigator.userAgent.includes('Mobi').
📐

Syntax

The basic syntax to detect a mobile browser uses the navigator.userAgent property, which is a string containing information about the browser and device. You check if this string contains the word 'Mobi', which is common in mobile user agents.

  • navigator.userAgent: A string with browser and device info.
  • includes('Mobi'): Checks if 'Mobi' is part of the string, indicating a mobile device.
javascript
const isMobile = navigator.userAgent.includes('Mobi');
💻

Example

This example shows how to detect a mobile browser and display a message accordingly.

javascript
const isMobile = navigator.userAgent.includes('Mobi');

if (isMobile) {
  console.log('You are using a mobile browser.');
} else {
  console.log('You are using a desktop browser.');
}
Output
You are using a mobile browser.
⚠️

Common Pitfalls

Some common mistakes when detecting mobile browsers include:

  • Relying on exact device names instead of general keywords like 'Mobi'.
  • Not accounting for tablets or unusual user agents.
  • Using deprecated or complex libraries when a simple check suffices.

Also, user agent strings can be spoofed, so detection is not 100% reliable.

javascript
/* Wrong way: Checking for exact device name */
const isMobileWrong = navigator.userAgent.includes('iPhone');

/* Right way: Using general keyword 'Mobi' */
const isMobileRight = navigator.userAgent.includes('Mobi');
📊

Quick Reference

Here is a quick summary of keywords to look for in navigator.userAgent to detect mobile devices:

KeywordDevice Type
MobiGeneral mobile devices (phones)
AndroidAndroid phones and tablets
iPhoneApple iPhones
iPadApple iPads (tablets)
MobileGeneral mobile devices
TabletTablets

Key Takeaways

Use navigator.userAgent.includes('Mobi') to detect most mobile browsers simply.
User agent detection is not perfect; some devices or browsers may not be detected correctly.
Avoid checking for exact device names; use general keywords for better coverage.
Consider tablets separately if needed by checking for 'Tablet' or 'iPad' keywords.
Keep detection code simple and test on real devices for best results.