JS Learning 9 (client-side detection)

Source: Internet
Author: User

Depending on the capabilities of each client, implementing the same functionality may require different implementations. This requires a variety of client-side detection methods. It is worth mentioning that the use of client-side detection is only a last resort, and try to use a common method to achieve the desired results.

Capability Testing

The goal of competency detection is to identify the browser's capabilities rather than identify specific browsers. As long as you determine that the current browser has this feature, you can implement the corresponding solution.
For example, there was no document.getElementById before IE5 ():

function getElement(id){         if (document.getElementById){                 returndocument.getElementById(id);         elseif (document.all){                 returndocument.all[id];     else {                 thrownew Error("No way to retrieve element!");         } }

This detects whether the function exists, and if so, represents the ability to use this feature. Here are two points to note: The most common features are first detected, which optimizes the code, which feature to use to detect which feature, and do not assume that there is another one for this feature.

More reliable ability to detect

The original capability test can tell if a feature exists, but it doesn't know if the feature is the one we want. Like what:

function isSortable(object){        return

The intent of this method is to detect whether the object has a sorting method, but for those objects that have the sort attribute, the function returns True as well. And in IE, it is an error for ActiveX objects to directly access functions as properties. So a better way is to detect if sort is a function:

function isSortable(object){          returntypeof"function"; }

But this can sometimes be problematic in IE:

    • Because DOM objects in IE are implemented using COM, it is possible to use TypeOf to detect a method that returns an object.
    • The ActiveX object is also a special case here, and using TypeOf for its methods is likely to return unknown

      So, the almighty approach is this:

function isHostMethod(object, property) {       vartypeofobject[property];       return t==‘function‘ || (!!(t==‘object‘object[property])) || t==‘unknown‘; } alert(isHostMethod("asdf","replace"));
Capability detection is not browser detection
var isFirefox = !!(navigator.vendor && navigator.vendorSub); var isIE = !!(document.all && document.uniqueID); 

These two examples exaggerate the effect of testing, and the detection of these attributes does not mean that the user is using this browser.
The goal of competency testing should be to choose the solution to the problem based on the features you need, rather than detecting what browser the user is using. And in the test to ensure that you want to use the ability to do exist, do not do too much speculation, code also do not make too much judgment.

// 确定浏览器是否支持Netscape风格的插件 var hasNSPlugins = !!(navigator.plugins && navigator.plugins.length);  // 是否有DOM1级别的能力 var hasDOM1 = !!(document.getElementById && document.createElement && document.getElementsByTagName);  
Quirks detection

Is the detection of browser bugs, depending on the bug, the detection method is different, but the basic idea is to use this bug function of the code, based on the results returned to determine whether there is a bug. For example, if an instance attribute exists in the IE8 with the same name as a non-enumerable prototype property, then the for-in statement is not recycled.

varfunction(){      varfunction(){} };         for (varin o) {         if"toString"){                     returnfalse;                 }         }      returntrue; }();
User Agent Detection

In each HTTP request, the user agent string is sent through the response header. The string can be accessed through navigator.useragent. On the client side, it is not recommended to use this method of detection, priority ranked behind the previous two kinds of detection.
The user-agent string is simply a chaotic world ... It's full of corporate gaming and technical compromises ...

User Agent string detection
varClient = function(){    //Identify the rendering engine    varEngine = {ie:0, Gecko:0Webkit:0, khtml:0, Opera:0, Ver:NULL};//Identify browser    varBrowser = {ie:0, Firefox:0Safari:0, Konq:0, Opera:0Chrome:0, Ver:NULL};//Identification platform    varSystem = {win:falseMac:false, X11:falseIphone:falseIpod:falseIpad:falseIos:falseAndroid:false, Nokian:false, winmobile:falseWii:falsePs:false};varUA = navigator.useragent;//opera is a disguise, so check it out first.    if(Window.opera)        {engine.ver = Browser.ver = Window.opera.version (); Engine.opera = Browser.opera =parsefloat(Engine.ver);//Include Gecko and khtml in WebKit, so check it first}Else if(/applewebkit\/(\s+)/. Test (UA)) {Engine.ver =RegExp["$"]; Engine.webkit =parsefloat(Engine.ver);//chrome using WebKit        if(/chrome\/(\s+)/. Test (UA)) {Browser.ver =RegExp["$"]; Browser.chrome =parsefloat(Browser.ver);//safari using WebKit}Else if(/version\/(\s+)/. Test (UA)) {Browser.ver =RegExp["$"]; Browser.safari =parsefloat(Browser.ver); }Else{//safari3 below cannot detect the version with the above code, use the following bar            varSafariversion =1;if(Engine.webkit < -) {safariversion =1; }Else if(Engine.webkit <312) {safariversion =1.2; }Else if(Engine.webkit <412) {safariversion =1.3; }Else{safariversion =2;        } Browser.safari = Browser.ver = safariversion; }//contains gecko in khtml, so you should check it first}Else if(/khtml\/(\s+)/. Test (UA) | |/konqueror\/([^;] +)/. Test (UA)) {engine.ver = Browser.ver =RegExp["$"]; engine.khtml = Browser.konq =parsefloat(Engine.ver);//Final detection khtml}Else if(/RV: ([^\)]+) \) gecko\/\d{8}/. Test (UA)) {Engine.ver =RegExp["$"]; Engine.gecko =parsefloat(Engine.ver);//Is not Firefox        if(/firefox\/(\s+)/. Test (UA)) {Browser.ver =RegExp["$"]; Browser.firefox =parsefloat(Browser.ver); }//ie features better detection}Else if(/msie ([^;] +)/. Test (UA)) {engine.ver = Browser.ver =RegExp["$"]; engine.ie = browser.ie =parsefloat(Engine.ver);    } browser.ie = engine.ie; Browser.opera = Engine.opera;//Identification platform    varp = navigator.platform; System.win = P.indexof ("Win") ==0; System.mac = P.indexof ("Mac") ==0; system.x11 = (P = ="X11") || (P.indexof ("Linux") ==0);if(System.win) {if(/win (?:d ows)? ([^do]{2}) \s? (\d+\.\d+)?. Test (UA)) {if(RegExp["$"] =="NT"){Switch(RegExp["$"]){ Case "5.0": System.win =" the"; Break; Case "5.1": System.win ="XP"; Break; Case "6.0": System.win ="Vista"; Break; Case "6.1": System.win ="7"; Break;default: System.win ="NT"; Break; }            }Else if(RegExp["$"] =="9x") {System.win ="ME"; }Else{System.win =RegExp["$"]; }}} System.iphone = Ua.indexof ("IPhone") >-1; System.ipod = Ua.indexof ("IPod") >-1; System.ipad = Ua.indexof ("IPad") >-1; System.nokian = Ua.indexof ("Nokian") >-1;//windows Mobile    if(System.win = ="CE") {system.winmobile = System.win; }Else if(System.win = ="Ph"){if(/windows Phone OS (\d+.\d+)/. Test (UA)) {System.win ="Phone"; System.winmobile =parsefloat(RegExp["$"]); }    }//IOS    if(System.mac && Ua.indexof ("Mobile") >-1){if(/cpu (?: IPhone)? OS (\d+_\d+)/. Test (UA)) {System.ios =parsefloat(RegExp.$1.Replace"_",".")); }Else{System.ios =2; }    }//Android    if(/android (\d+\.\d+)/. Test (UA)) {system.android =parsefloat(RegExp.$1); } system.wii = Ua.indexof ("Wii") >-1; System.ps =/playstation/i. Test (UA);return{engine:engine, Browser:browser, System:system};} (); alert (Client.browser.firefox);

JS Learning 9 (client-side detection)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.