JavaScript

[JavaScript] PC / Mobile 디바이스 구분하기

효니님 2023. 7. 5. 18:16
728x90

 

01. navigator.userAgent를 이용하여 확인하는 방법

참고 👉 MDN | Navigator: userAgent property

 

🌵 예시 코드

function isMobile() {
  return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  );
}

if (isMobile()) {
  // 모바일일 경우
} else {
  // 모바일 외
}

 

🌵 예시 코드

function isMobile() {
  const userAgent = navigator.userAgent;
  if (
    userAgent.match(
      /iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson/i
    ) != null ||
    userAgent.match(/LG|SAMSUNG|Samsung/) != null
  ) {
    return true;
  } else {
    return false;
  }
}

 

🌵 예시 코드

const isMobile = /Mobi/i.test(window.navigator.userAgent);
// "Mobi" 가 User agent에 포함되어 있으면 모바일

 

 

02. JavaScript 터치 이벤트를 이용하여 확인하는 방법

JavaScript의 ontouchstart 이벤트 사용 여부로 모바일 디바이스를 판별합니다.

(터치 스크린이 있는 디바이스에서만 동작합니다.)

const isMobile = (document.documentElement의 'ontouchstart' && navigator.userAgent.match(/Mobi/));
const isTouchDevice = (navigator.maxTouchPoints || 'ontouchstart' in document.documentElement);

 

03. 스크린 사이즈를 감지하여 확인하는 방법

스크린 사이즈를 확인하여 모바일 디바이스를 감지할 수 있습니다.

 

🌵 JavaScript

const isMobile = window.matchMedia(
  "only screen and (max-width: 768px)"
).matches;

if (isMobile) {
  // mobile only
}

 

🌵 jQuery

if ($(window).width() <= 768) {
  // mobile only
}
728x90