原型库中的浏览器和版本?

Evi*_*Syn 14 javascript browser-detection prototypejs

我习惯使用Atlas.最近我开始转换到jQuery,有时甚至是原型.我目前正在研究的项目是使用原型.

在Prototype中,有一种简单的方法来获取浏览器名称和版本吗?我查看了API文档,似乎无法找到它.

sep*_*ehr 18

作为nertzy答案的完成,您可以使用以下功能添加检测IE版本的功能:

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 7;
Prototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;
Run Code Online (Sandbox Code Playgroud)

另一方面,您还必须在服务器端检测用户代理详细信息.无论如何,浏览器检测是编写跨浏览器脚本的严重缺陷策略,只有在浏览器功能检测失败时才能使用.用户很容易改变他/她的用户代理详细信息.


Gra*_*ins 7

Prototype提供了一些标记,您可以检查以了解哪个浏览器正在运行.请记住,检查您希望使用的功能而不是检查特定浏览器是更好的做法.

以下是prototype.js源树中当前的浏览器和功能检测部分:

var Prototype = {
  Browser: {
    IE:     !!(window.attachEvent &&
      navigator.userAgent.indexOf('Opera') === -1),
    Opera:  navigator.userAgent.indexOf('Opera') > -1,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && 
      navigator.userAgent.indexOf('KHTML') === -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    SelectorsAPI: !!document.querySelector,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions: 
      document.createElement('div')['__proto__'] &&
      document.createElement('div')['__proto__'] !== 
        document.createElement('form')['__proto__']
  },
}
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过调查当前浏览器是否为IE来检查其值Prototype.Browser.IE,或者更具有未来兼容性,并检查特定功能,如XPath Prototype.BrowserFeatures.XPath.


Rem*_*arp 3

你是对的 - 原型不提供用于确定浏览器名称或版本的实用程序。

如果您特别需要将浏览器信息作为插件获取,我建议添加以下内容(直接取自 jQuery):

var Browser = Class.create({
  initialize: function() {
    var userAgent = navigator.userAgent.toLowerCase();
    this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
    this.webkit = /webkit/.test( userAgent );
    this.opera = /opera/.test( userAgent );
    this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
    this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 你有点不正确,Prototype 确实提供了一个用于猜测浏览器名称的实用程序,如下所示。猜测确实是您能做的最好的事情,因为任何浏览器都可能对其用户代理字符串撒谎。 (2认同)