본문 바로가기

JavaScript

[JavaScript] 모바일 장치 구분

반응형



모바일 장치 구분



스마트폰으로 http://naver.com에 접속하면 자동으로 http://m.naver.com으로 이동한다.

네이버 페이지에 접속한 사용자가 스마트폰을 사용하는지 확인해 스마트폰이면

http://m.naver.com으로 이동시키기 때문이다.




스마트폰을 확인할 때 일반적으로 navigator 객체의 userAgent 속성을 사용한다.

userAgent 속성은 현재 웹 페이지를 실행하는 웹 브라우저의 정보를 나타낸다.


 userAgent.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>모바일 장치 구분</title>
</head>
<script>
    var userAgent = navigator.userAgent;
    alert(userAgent);
</script>
</html>

 출력화면



스마트폰 환경에서 위 코드를 실행하면 위와같이 경고창에 브라우저와 관련된 정보가 표시된다.


스마트폰 브라우저의 useAgent 속성에는 브라우저를 구분할 수 있는 고유한 문자열이 있다.


 ● iPhone

 ● iPad

 ● iPod

 ● Opera Mobi

 ● Opera Mini

 ● Nokia

 ● Android

 ● WebOS

 ● Windows CE

 ● BlackBerry

 ● IEMobile

 ● SonyErricsson


위와 같이 아이폰은 useAgent 속성에 iPhone이라는 문자열이 있고 윈도우폰7에는 IEMobile이라는 문자열이 있다.


위의 키워드를 사용하면 아래 예제와 같이 각각의 스마트폰을 구분할 수 있다.



 smartPhon_Section.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>스마트폰 구분</title>
</head>
<script>
   
    // 변수를 선언합니다.
    var smartPhones = [
       
        'iphone', 'ipad', 'windows ce', 'android', 'blackberry', 'nokia',
        'webos', 'opera mini', 'sonyerricsson', 'opera mobi', 'iemobile'
    ];

    for(var i in smartPhones) {
       
        if(navigator.userAgent.toLowerCase().match(new RegExp(smartPhones[i]))) {
           
            alert('This is Smart Phone..!');
        }
    }
</script>
</html>

 출력화면


데스크톱에서 실행하면 아무 반응도 없지만, 스마트폰으로 접속하면 'Thi is Smart Phone..!'이라는 경고창이 뜬다.







반응형