본문 바로가기
마루아라는 개발쟁이

mobile과 pc 디바이스 자바스크립트로 구분하는 쉬운방법

by 마루아라 이야기 2024. 6. 21.

자바스크립트로 구현할 수 있는 방법

 

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
    window.onload=function deviceCheck() {

        const user = navigator.userAgent;

        if ( user.indexOf("iPhone") > -1 || user.indexOf("Android") > -1 ) {
            console.log("mobile버젼");
            console.log(user);    
        }else{
            console.log("pc버젼");
            console.log(user);
        }
    }
</script>
</head>
<body>

</body>
</html>
navigator.userAgent 는 자바스크립트 내장함수로 개발자모드로 Console창에 입력하면 아래와 같이 현재 디바이스의 정보를 보여준다.

navigator.userAgent를 user에 담아서 indexOf("iPhone" 또는 "Android") 함수를 통하여 괄호안에 있는 단어를 찾으면 index숫자를 반환하고 없으면 -1을 반환한다.

728x90
반응형
LIST