19五月/113
利用 UserAgnet 判斷是否為行動裝置瀏覽網頁
前言
因為工作上需求會要判斷使用者是不是使用行動裝置(e.g. iPhone、Android 手機)來瀏覽網頁,因此寫了個類別來判斷 UserAgent 是不是行動版裝置瀏覽。
說明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class UserAgentUtility { private static string[] mobiles = new[] { "midp", "j2me", "avant", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml","pda", "windows ce", "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up.b", "audio", "sie-", "sec-", "samsung", "htc", "mot-", "mitsu", "sagem", "sony", "alcatel", "lg", "eric", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda","sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "dddi", "moto", "iphone", "android", "iPod", "incognito", "webmate", "dream", "cupcake", "webos", "s8000", "bada", "googlebot-mobile" }; /// <summary> /// 判斷是否為行動版瀏覽器 /// </summary> /// <param name="UserAnget"></param> /// <returns></returns> public static bool isMobile(string UserAnget) { if (string.IsNullOrEmpty(UserAnget)) return false; foreach (var item in mobiles) { if (UserAnget.ToLower().IndexOf(item) != -1) return true; } return false; } } |
2011/09/23 16:23 補充:JavaScript 版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<script type="text/javascript"> var mobiles = new Array ( "midp", "j2me", "avant", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows ce", "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up.b", "audio", "sie-", "sec-", "samsung", "htc", "mot-", "mitsu", "sagem", "sony", "alcatel", "lg", "eric", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "dddi", "moto", "iphone", "android", "iPod", "incognito", "webmate", "dream", "cupcake", "webos", "s8000", "bada", "googlebot-mobile" ) var ua = navigator.userAgent.toLowerCase(); var isMobile = false; for (var i = 0; i < mobiles.length; i++) { if (ua.indexOf(mobiles[i]) > 0) { isMobile = true; break; } } </script> |
結論
現在智慧型手機和平板越來越多了,也會有很多需求是針對行動裝置設計行動版網頁,並且在行動裝置瀏覽到網頁的時候自動轉換到行動版網頁,因此這個類別應該會對不少讀者有幫助,也希望有讀者可以分享還有哪些方式可以來判斷囉!
九月 21st, 2011 - 15:45
老師您好
請教一下要如何判斷手機版網頁?
可適用在兩個html的判斷嗎?
例如:pc.html和mobile.html這兩個網頁檔
當我用iphone讀取pc.html時能夠自動轉換讀取mobile.html
有辦法達成嗎?
謝謝!
十一月 23rd, 2011 - 12:34
老師不好意思打擾,請問老師 我在您"2011/09/23 16:23 補充:JavaScript 版本"
並沒有看到樓上朋友問的
"當我用iphone讀取pc.html時能夠自動轉換讀取mobile.html"
是否可以請老師再詳細說明一下 我比較笨>"<
謝謝老師了
三月 8th, 2012 - 20:57
大大您好
非常感謝您的分享
這個真的對我有很大的幫助
不過我在實作的時候發現有一個問題
C# 版本在判斷的時候 UserAgent 會傳入有區分大小寫的字串
導致全部被判斷成 not mobile
建議可以加上 ToLower
if (UserAnget.ToLower().IndexOf(item) != -1)
也可以參考http://detectmobilebrowsers.com/
有用 Regex 寫的