第一種, jquery
var deviceAgent = navigator.userAgent.toLowerCase(); var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/); if(agentID.indexOf("iphone")>=0){ alert("iphone"); } if(agentID.indexOf("ipod")>=0){ alert("ipod"); } if(agentID.indexOf("ipad")>=0){ alert("ipad"); } if(agentID.indexOf("android")>=0){ alert("android"); }
<!DOCTYPE html><html><head><meta name="viewport" content="initial-scale=1.0, user-scalable=no" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><style type="text/css"> html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% }</style><script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script><script type="text/javascript"> function initialize() {var useragent = navigator.userAgent;if (useragent.indexOf('iPhone') != -1) {alert("iPhone");} else if(useragent.indexOf('iPad') != -1 ) {alert("iPad");} else if(useragent.indexOf('Android') != -1 ) {alert("Android");} else {alert("其他平台");} }</script></head><body onload="initialize()"></body></html>
第二種 Java:
Enumeration typestr = request.getHeaderNames(); String s1 = request.getHeader("user-agent");if(s1.contains("Android")) {System.out.println("Android移動用戶端");} else if(s1.contains("iPhone")) {System.out.println("iPhone移動用戶端");} else if(s1.contains("iPad")) {System.out.println("iPad用戶端");} else {System.out.println("其他用戶端");}
整個頁面 index.jsp:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><link rel="shortcut icon" href="favicon.ico"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><%Enumeration typestr = request.getHeaderNames(); String s1 = request.getHeader("user-agent");if(s1.contains("Android")) {System.out.println("Android移動用戶端");} else if(s1.contains("iPhone")) {System.out.println("iPhone移動用戶端");} else if(s1.contains("iPad")) {System.out.println("iPad用戶端");} else {System.out.println("其他用戶端");}%></body></html>
第二種情況測試下來,一般情況下可以滿足需要,遇到像UC瀏覽器這些第三方瀏覽器,可能就不準了!
python, php, ror, .Net這些的話都可以借鑒第二種方式!