How to determine the Opera browser using JavaScript

后端 未结 6 906
清歌不尽
清歌不尽 2020-12-14 17:09

I want to determine that the browser of the client machines in Opera or not using JavaScript, how to do that?

6条回答
  •  自闭症患者
    2020-12-14 17:54

    In Prototype.js, we use this inference:

    var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
    

    This essentially checks that window.opera object exists and its internal [[Class]] value is "Opera". This is a more solid test than just checking for window.opera existence, since there's much less chance of some unrelated global opera variable getting in the way and resulting in false positives.

    Speaking of unrelated global variable, remember that in MSHTML DOM, for example, elements can be resolved by id/name globally; this means that presence of something like foo in a markup will result in window.opera referencing that anchor element. There's your false positive...

    In other words, test [[Class]] value, not just existence.

    And of course always think twice before sniffing for browser. Oftentimes there are better ways to solve a problem ;)

    P.S. There's a chance of future versions of Opera changing [[Class]] of window.opera, but that seems to be unlikely.

提交回复
热议问题