어떤 웹사이트를 방문했는데 모바일 기기로 보았을 때와 노트북으로 보았을 때의 화면이 다르게 나타났다. 반응형 웹페이지로 만들었다고 생각했는데 개발자도구로 화면을 줄여도 디자인이 달라지지 않았다. 어떻게 만들었는지 궁금했다.
모바일 기기를 감지하기 위해 접근할 수 있는 방법은 window 객체의 navigator 속성 안에 userAgent를 통해 접근할 수 있다. 이 곳에서 사용자가 어떤 운영체제, 브라우저에서 접근했는지에 대한 정보를 알 수가 있다.
활용
// detectMobileDevice 함수는
// 정규식 배열을 만들고 해당 정규식 중 하나라도 통과하면 해당 기기를 모바일 기기로 판단하는 함수이다.
const detectMobileDevice = (agent:string) => {
const mobileRegex = [
/Android/i,
/iPhone/i,
/iPad/i,
/iPod/i,
/BlackBerry/i,
/Windows Phone/i
]
return mobileRegex.some(mobile => agent.match(mobile))
}
const isMobile = detectMobileDevice(window.navigator.userAgent)
if (isMobile) {
// true
console.log('current device is mobile')
} else {
// false
console.log('current device is not mobile')
}