要想写出跨浏览器的javascript,就必须懂得嗅探技术。这是浏览器大战遗留下的大地雷,事已如此,只好认命,乖乖写分支结构吧,函数就是这样不知不觉中变长的。
先看单一浏览器的判断,我们没有必须去找navigator.userAgent的麻烦,我在国外的博客网站收集了如下hack,短小精悍:
ie = !+ "/v1" ;
02. ie = ''/v'' == ''v'' ;
03. ie = 0 //@cc_on+ 1 ;
04. ie = !! top .execScript;
05. ie = /*@cc_on!@*/ ! 1 ;
06. ie 8 = !!window.XDomainRequest;
07.
08. //我自创的,如果是IE,会返回 6 , 7 , 8 代表ie 6 ,ie 7 ,ie 8 ,否则返回 1
09. IEVersion = ( " " + ( /*@cc_on @_jscript_version @*/ -1 )).slice( -1 )
10.
11. //基于条件编译的嗅探脚本,还有如下几个:
12. IE 8 =@cc_on @_jscript_version == 5.8 ? true : @false
13. IE 7 =@cc_on @_jscript_version == 5.7 ? true : @false
14. IE 6 =@cc_on @_jscript_version == 5.6 ? true : @false
15. IE 55 =@cc_on @_jscript_version == 5.5 ? true : @false
16.
17.
18. ff = /a/[ -1 ]== ''a'' ;
19. ff 3 = (function x(){})[ -5 ]== ''x'' ;
20. ff 2 = (function x(){})[ -6 ]== ''x'' ;
21.
22. safari=/a/.__proto__== ''//'' ;
23. safari = window.openDatabase;
24.
25. chrome=/source/.test((/a/.toString+ '''' ));
26.
27. opera=!!window.opera ;
28. opera=/^function (/.test([].sort);
|
还有判断
//出处:http://www.cnblogs.com/xiarugu/archive/ 2009 / 02 / 02 / 1382293 .html
02. function IsMaxthon()
03. {
04. try{
05. window.external.max_invoke( "GetHotKey" );
06. return true;
07. }catch(ex){
08. return false;
09. }
10. }
11. alert(IsMaxthon());
|
//出处:http://bbs.maxthon.cn/archiver/?tid -148353 .html
02. try{
03. if(external.max_version.indexOf( "1." )== 0 ){
04. var isMaxthon 1 = 1 ;
05. }else{
06. var isMaxthon 1 = 0 ;
07. }
08. }catch(e){
09. var isMaxthon 1 = 0 ;
10. }
|
如果是想搞比较复杂的UI或者类库,对于浏览器的判断就要更严格一些,不能像上面那样游兵散勇。
B=(function x(){})[ -5 ]== ''x'' ? ''FF3'' :(function x(){})[ -6 ]== ''x'' ? ''FF2'' :/a/[ -1 ]== ''a'' ? ''FF'' : ''/v'' == ''v'' ? ''IE'' :/a/.__proto__== ''//'' ? ''Saf'' :/s/.test(/a/.toString)? ''Chr'' :/^function /(/.test([].sort)? ''Op'' : ''Unknown'' |
在Ext3的源码中能找出如下现整的嗅探脚本:
ua = navigator.userAgent.toLowerCase(),
02. check = function(r){
03. return r.test(ua);
04. },
05. isOpera = check(/opera/),
06. isChrome = check(/chrome/),
07. isWebKit = check(/webkit/),
08. isSafari = !isChrome && check(/safari/),
09. isSafari 2 = isSafari && check(/applewebkit// 4 /), // unique to Safari 2
10. isSafari 3 = isSafari && check(/version// 3 /),
11. isSafari 4 = isSafari && check(/version// 4 /),
12. isIE = !isOpera && check(/msie/),
13. isIE 7 = isIE && check(/msie 7 /),
14. isIE 8 = isIE && check(/msie 8 /),
15. isIE 6 = isIE && !isIE 7 && !isIE 8 ,
16. isGecko = !isWebKit && check(/gecko/),
17. isGecko 2 = isGecko && check(/rv: 1 /. 8 /),
18. isGecko 3 = isGecko && check(/rv: 1 /. 9 /),
|
好了,基本就是这样了,如果你有什么发现,也敬请拿出来分享一下!