본문 바로가기
  • 오늘도 한걸음. 수고많았어요.^^
  • 조금씩 꾸준히 오래 가자.ㅎ
IT기술/javascript

[javascript] 모바일 환경 pc환경 구분하기

by 미노드 2024. 1. 23.

웹사이트를 개발하다보면 모바일 환경인지, PC환경인지에 따라서
소스를 분리시켜야 하는 경우가 생기기도 합니다.

이런 기능을 쓰는 이유는, 웹과 모바일 환경에서 사이트를 접속하며, 상대적으로 가벼운 웹사이트를 요구하는 모바일 환경에 대응하기 위한 부분도 있고, 모바일용 페이지와 웹용 페이지를 별도로 만들지 않고 운영하기 위한 부분도 있기 때문입니다.

요즘은 이런 기능을 위한 별도 js 스크립트도 개발되어 배포되고 있다고 하지만, 단순히 적용 가능한 방법을 기술해보려 합니다.

바로 자바스크립트 내장함수인 navigator.userAgent  를 이용하는 것입니다.
이는 여러 페이지에서 접속되는 디바이스를 구분하여 출력하는 함수인데, 이것만 가지고 모바일 환경인지 구분하는 것은
현대에선 좋은 방법이라고 보지 않을 수도 있을거라 생각이 들지만, 그럼에도 단순한 기능구현에선 유용한 방법이라 생각되어 정리해 봤습니다.

javascript 에서 navigator.userAgent 를 통해 접속기기 종류를 볼 수 있는데, 이 기능을 활용하여, PC환경에서 접속하는지, 모바일환경에서 접속하는지 구분하여 조건을 나눌 수 있습니다.

예시소스

<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="color-scheme" content="light dark">
<script type="text/javascript">if (!window.T) { window.T = {} }
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { // Mobile
  console.log('true')
} else { // PC
  console.log('false')
}
 
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;
    }
}
 
if(isMobile()) {
alert('isMobile()') // Mobile
console.log('isMobile()')
    // mobile only code
 
} else { // PC
alert('isPc()')
console.log('isPc()')
    // pc only code
}</script>
</head>
<body><div class="line-gutter-backdrop"></div>
</body>

</html>

또다른 방법으로 navigator.platform 명령을 통해 접속한 플랫폼이 윈도우나 매킨토시이면 PC, 그게 아니면 Mobile환경 이라고 인식하여 구분할 수 있습니다.
navigator.platform 명령의 결과는 다음처럼 나올 수 있습니다.

Win16 : 16비트 윈도위기반 컴퓨터
Win32 : 32비트 윈도위기반 컴퓨터
Win64 : 64비트 윈도위기반 컴퓨터
Mac : 매킨토시컴퓨터
MacIntel  :  인텔CPU 를 가진 매킨토시 컴퓨

이를 소스로 예시를 만들어보면 다음과 같습니다.

<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="color-scheme" content="light dark">
<script type="text/javascript">if (!window.T) { window.T = {} }
// MOBILE 구별
var mobileKeyWords = new Array('iPhone', 'iPod', 'BlackBerry', 'Android', 'Windows CE', 'Windows CE;', 'LG', 'MOT', 'SAMSUNG', 'SonyEricsson', 'Mobile', 'Symbian', 'Opera Mobi', 'Opera Mini', 'IEmobile');
  for (var word in mobileKeyWords) {
    if (navigator.userAgent.match(mobileKeyWords[word]) != null) {
    	console.log('mobileKeyWords 구분으로 mobile true')
   		break;
	
  }else {
	console.log(mobileKeyWords[word]+' False   mobile False')
  }
}


function deviceCheck() {
    // 디바이스 종류 설정
    var pcDevice = "win16|win32|win64|mac|macintel";
 
    // 접속한 환경 확인
    if ( navigator.platform ) {
        if ( pcDevice.indexOf(navigator.platform.toLowerCase()) < 0 ) {
            console.log('MOBILE');
			return true;
        } else {
            console.log('PC');
			return false;
        }
    }
}
 
if(deviceCheck()) {
alert('isMobile()') // Mobile
console.log('isMobile()')
    // mobile only code
 
} else { // PC
alert('isPc()')
console.log('isPc()')
    // pc only code
}</script>
</head>
<body><div class="line-gutter-backdrop"></div>
</body>

</html>

 

참조 블로그: https://sereni-ty.tistory.com/106