জাভাস্ক্রিপ্টে মোবাইল ব্রাউজার ডিটেক্ট করার কোড নিচে দেওয়া হলো।
উদাহরণ
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.sample { font-size: 18px; font-weight: 500; }
</style>
</head>
<body>
<h1>Detecting a mobile browser</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see if it is a mobile device or not</h3>
<script>
let fillEle = document.querySelector(".sample");
document.querySelector(".Btn").addEventListener("click", () => {
var checkMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (checkMobile) {
fillEle.innerHTML = "This is a mobile device";
} else {
fillEle.innerHTML = "This is not a mobile device";
}
});
</script>
</body> </html>
ব্যাখ্যা
navigator.userAgentব্রাউজারের ইউজার এজেন্ট স্ট্রিং রিটার্ন করে- রেজেক্স
/iPhone|iPad|iPod|Android/iদিয়ে মোবাইল ডিভাইস সিগনেচার চেক করা হয় test()মেথডtrue/falseরিটার্ন করে
সীমাবদ্ধতা এবং ভালো পদ্ধতি
User Agent Sniffing অনিশ্চিত এবং মেইনটেইন করা কঠিন। ভালো পদ্ধতি:
- Feature Detection:
'ontouchstart' in window,navigator.maxTouchPoints > 0 - CSS Media Queries:
@media (pointer: coarse)(টাচ স্ক্রিন) - Responsive Design: ভিউপোর্ট ওপ্টিমাইজেশন
বेहতর ডিটেকশন ফাংশন
function isMobileDevice() {
return (typeof window.orientation !== "undefined") ||
(navigator.userAgent.indexOf("IEMobile") !== -1) ||
/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent);
}