2014-02-13 3 views
15

현재 데스크톱 및 태블릿 플랫폼에서 다른 기능을 제공하는 클라이언트 웹 사이트에 대해 일부 JS 작업을 개발 중입니다. 다음을 고려하십시오 :JavaScript 모바일/태블릿 사용자 에이전트 확인 방법

if(! navigator.userAgent.match(/Android/i) && 
      ! navigator.userAgent.match(/webOS/i) && 
      ! navigator.userAgent.match(/iPhone/i) && 
      ! navigator.userAgent.match(/iPod/i) && 
      ! navigator.userAgent.match(/iPad/i) && 
      ! navigator.userAgent.match(/Blackberry/i)) 
    { 
     // do desktop stuff 

    } else if (navigator.userAgent.match(/iPad/i)) 
    { 
     // do tablet stuff 

    } 

현재 "나는 안드로이드"에 대한 확인이 다소 문제가있는 것처럼 보일뿐입니다. 매우 광범위한 용어입니다. 안드로이드 타블렛 & JS를 사용하여 모바일 태블릿을 구별하는 알려진 방법이 있습니까?

많은 감사, 마일스는

+2

이 질문에 대한 의견에 따르면 : http://stackoverflow.com/questions/5341637/how-do-detect-android-tablets-in-general-useragent '모바일' UA에서. 이 문제를 해결할 수있는 방법은 없나요? – Myles

답변

15

첫째 - 조건

if (navigator.userAgent.match(/iPad/i)) { // do tablet stuff } else if(navigator.userAgent.match(/Android|webOS|iPhone|iPod|Blackberry/i)) { // do mobile stuff } else { // do desktop stuff } 

둘째

을 개선 누락 된 키워드를 추가 :

if (navigator.userAgent.match(/Tablet|iPad/i)) 
{ 
    // do tablet stuff 
} else if(navigator.userAgent.match(/Mobile|Windows Phone|Lumia|Android|webOS|iPhone|iPod|Blackberry|PlayBook|BB10|Opera Mini|\bCrMo\/|Opera Mobi/i)) 
{ 
    // do mobile stuff 
} else { 
    // do desktop stuff 
} 

그리고 세 번째, 이것은이다 우리의 실제 탐지 스크립트 E :

https://jsfiddle.net/oriadam/ncb4n882/

var 
    ua = navigator.userAgent, 
    browser = /Edge\/\d+/.test(ua) ? 'ed' : /MSIE 9/.test(ua) ? 'ie9' : /MSIE 10/.test(ua) ? 'ie10' : /MSIE 11/.test(ua) ? 'ie11' : /MSIE\s\d/.test(ua) ? 'ie?' : /rv\:11/.test(ua) ? 'ie11' : /Firefox\W\d/.test(ua) ? 'ff' : /Chrome\W\d/.test(ua) ? 'gc' : /Chromium\W\d/.test(ua) ? 'oc' : /\bSafari\W\d/.test(ua) ? 'sa' : /\bOpera\W\d/.test(ua) ? 'op' : /\bOPR\W\d/i.test(ua) ? 'op' : typeof MSPointerEvent !== 'undefined' ? 'ie?' : '', 
    os = /Windows NT 10/.test(ua) ? "win10" : /Windows NT 6\.0/.test(ua) ? "winvista" : /Windows NT 6\.1/.test(ua) ? "win7" : /Windows NT 6\.\d/.test(ua) ? "win8" : /Windows NT 5\.1/.test(ua) ? "winxp" : /Windows NT [1-5]\./.test(ua) ? "winnt" : /Mac/.test(ua) ? "mac" : /Linux/.test(ua) ? "linux" : /X11/.test(ua) ? "nix" : "", 
    mobile = /IEMobile|Windows Phone|Lumia/i.test(ua) ? 'w' : /iPhone|iP[oa]d/.test(ua) ? 'i' : /Android/.test(ua) ? 'a' : /BlackBerry|PlayBook|BB10/.test(ua) ? 'b' : /Mobile Safari/.test(ua) ? 's' : /webOS|Mobile|Tablet|Opera Mini|\bCrMo\/|Opera Mobi/i.test(ua) ? 1 : 0, 
    tablet = /Tablet|iPad/i.test(ua), 
    touch = 'ontouchstart' in document.documentElement; 

편집 : 태블릿과 아이 패드가 mobiletablet 모두 간주됩니다

참고. 터치, 마우스 및 키보드가 모두있는 랩톱이 있습니다. 다른 말로하면 좋은 프로그래머는 touch에 의존하지 않고 대신 모든 세 가지 입력 방법을 모두 지원합니다.

+0

아직도 정확한가? iPad와 일치하지 않게하려면 목록에서 '모바일'을 삭제해야했습니다. 감사합니다 –

+0

@MarioParra 태블릿과 iPads는 모두 '모바일'이고 '태블릿'입니다 – oriadam

+0

... 그래서 당신이 말하는 것은 ... "할인이 필요합니까?" – Relic