JAVASCRIPT -

모바일기기 확인(mobile detect)

  • -

📲  자바스크립트 모바일 기기 확인(javascript mobile detect)

안녕하세요 오늘은 자바스크립트로 모바일 기기를 체크하여 리다리랙트 시키는 방법에 대해서 소계 해드릴게요
이것은 하나의 웹 사이트에서 PC 도메인, mobile 도메인이 각각 다를때 사용하는것이 좋습니다.

아래 코드는 인터넷에 떠돌고 있는 흔하고, 좋지 않은 코드입니다.
이 코드를 좀 더 짧게 작성해보겠습니다.

// 💩
<script type="text/javascript">
	function isMobile(){
            var 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()){
		location.href = "/mobile/index.html";	//모바일페이지
	} else {
		location.href = "/main.html";		//PC용 페이지
	}
</script>

자바스크립트의 화살표 함수, 삼항 연사자를 이용해서 3줄로 만들었습니다.

// ✅
<script type="text/javascript">
	const isMobile = () => /iPhone|iPod|Android|Windows CE|BlackBerry|Symbian|Windows Phone|webOS|Opera Mini|Opera Mobi|POLARIS|IEMobile|lgtelecom|nokia|SonyEricsson|LG|SAMSUNG|Samsung/i;
	const UserAgent = navigator.userAgent;
	UserAgent.match(isMobile()) !== null ? location.href = "m.index.html" : location.href = "pcurl.html"
</script>

 

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.