The Simplest way is using vanilla JavaScript navigator API to detect mobile or tablet in HTML webpage. You have to regex (regular expression) in the query.
You can also use a 3rd party library such as wurfl.io:- https://web.wurfl.io/#wurfl-js
1 2 3 |
if (WURFL.is_mobile === true && WURFL.form_factor === "Tablet") { // targetSmartPhoneDevices(); } |
Example of JavaScript detect mobile or tablet
Using a console log to print message, IT will print message for tablet and mobile.
You can use it detect if the device is ONLY tablet or mobile.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <html> <head> <script type="text/javascript"> const userAgent = navigator.userAgent.toLowerCase(); var isMobile = /iPhone|Android/i.test(navigator.userAgent); console.log(isMobile); const isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(userAgent); console.log(isTablet) if(isMobile) { console.log("Mobile") }else if(isTablet){ console.log("Tablet") } </script> </head> <body> </body> </html> |
Output:

All major browser provides a very useful API to know the user’s device and the browser details.
1 |
window.navigator.userAgent |
Do comment if you have better example or doubts or suggestions this topic.
Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version