`
bird12010
  • 浏览: 7404 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

《javascript高级程序设计》学习笔记9 客户端检测

阅读更多

不到万不得已不要使用客户端检测。

 

9.1能力检测

目标不是识别特定的浏览器,而是识别浏览器的能力。

     window.onload = function(){
        
            function getWindowWidth(){
                if (window.innerWidth){
                    return window.innerWidth;
                } else if (document.documentElement.clientWidth){
                    return document.documentElement.clientWidth;
                } else if (document.body.clientWidth){
                    return document.body.clientWidth;
                }
            }
            
                    
            //确定浏览器是否有Netscape插件
            var hasNSPlugins = !!(navigator.plugins && navigator.plugins.length);
            
            //浏览器是否具有基本的DOM1级功能
            var hasDOM1 = !!(document.getElementById && document.createElement && 
                           document.getElementsByTagName);
            
            alert("Window width: " + getWindowWidth());
            alert("Supports Netscape plugins? " + hasNSPlugins);
            alert("Supports Core DOM 1? " + hasDOM1);
        }

 

9.2 怪癖检测

想要知道浏览器存在什么缺陷

        var hasDontEnumQuirk = function(){
        
            var o = { toString : function(){} };
            for (var prop in o){
                if (prop == "toString"){
                    return false;
                }
            }
        
            return true;
        }();

        var hasEnumShadowsQuirk = function(){
        
            var o = { toString : function(){} };
            var count = 0;
            for (var prop in o){
                if (prop == "toString"){
                    count++;
                }
            }
        
            return (count > 1);
        }();

        alert(hasDontEnumQuirk);
        alert(hasEnumShadowsQuirk);

 

9.2 用户代理检测

通过检测用户代理字符串来确定实际使用的浏览器。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics