Main Page

Detecting Opera

Detecting Opera
The simplest and best way to begin browser detection is to start with the
problem
browsers, such as
Opera and Safari. If you determine that a browser is not one of these, it is much easier to determine
when a browser is legitimately IE or Mozilla.
To begin, consider the possible Opera user-agent strings:
Opera/7.54 (Windows NT 5.1; U)
Mozilla/5.0 (Windows NT 5.1; U) Opera 7.54
Mozilla/4.78 (Windows NT 5.1; U) Opera 7.54
Mozilla/3.0 (Windows NT 5.1; U) Opera 7.54
Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Opera 7.54
One thing that jumps out right away is that each of these strings has the word
“Opera”
. So the easiest
way to determine if the browser is Opera is just to search for that string:
var isOpera = sUserAgent.indexOf(“Opera”) > -1;
When you know you have an Opera browser, you can go ahead and determine the actual version. The
first step is to define several variables to test for the various versions of Opera.
To determine what version of Opera is being used, you can define some variables:
var isMinOpera4 = isMinOpera5 = isMinOpera6 = isMinOpera7 = isMinOpera7_5 = false;
This code uses compound assignment to set each variable to an initial value of
false
, ensuring that if
the browser is Netscape, these variables return the correct value.
Naturally, you shouldn’t even bother setting these variables unless the browser has been identified as
Opera, so any further evaluation of the browser version needs to take place inside of an
if
statement:
if (isOpera) {
//version detection here
}
Because of Opera’s disguises, you have two different ways to determine the browser version. If Opera is
using its own user-agent string, the version is contained in
fAppVersion
, which was defined earlier.
You can check to see if Opera is using a disguise by checking
navigator.appName
; if it equals
“Opera”
,
then the browser isn’t using a disguise.
You could also use a regular expression to do this check; however, regular expres-
sions aren’t supported by some earlier browsers and could cause an error when the
line is executing. Using
indexOf()
ensures that this line works because the method
has been included since the very first version of JavaScript.
237
Browser and Operating System Detection
11_579088 ch08.qxd 3/28/05 11:38 AM Page 237


JavaScript EditorFree JavaScript Editor     Ajax Editor


©