18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

Just as when you are determining the version of a disguised Opera, using a regular expression is the easiest<br />

way to extract IE’s version from the user-agent string:<br />

var reIE = new RegExp(“MSIE (\\d+\\.\\d+)”);<br />

Once again, the pattern looks for one or more numbers, followed by a decimal point, followed by one or<br />

more numbers. Putting that expression into practice, you end up with this code:<br />

if (isIE) {<br />

var reIE = new RegExp(“MSIE (\\d+\\.\\d+);”);<br />

reIE.test(sUserAgent);<br />

var fIEVersion = parseFloat(RegExp[“$1”]);<br />

}<br />

isMinIE4 = fIEVersion >= 4;<br />

isMinIE5 = fIEVersion >= 5;<br />

isMinIE5_5 = fIEVersion >= 5.5;<br />

isMinIE6 = fIEVersion >= 6.0;<br />

And that’s all it takes to detect Internet Explorer. This code works equally well on Windows and<br />

Macintosh. Next up is IE’s main competitor, Mozilla.<br />

Detecting Mozilla<br />

By now, you should be familiar with how this works. Refresh your memory with the Mozilla user-agent<br />

string:<br />

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:0.9.4) Gecko/20011128<br />

Netscape6/6.2.1<br />

To be thorough, take a look at the Opera user-agent string when it is disguised as Mozilla 5.0:<br />

Mozilla/5.0 (Windows NT 5.1; U) Opera 7.54<br />

<strong>For</strong>tunately, you have plenty of ways to determine that this is Mozilla. The glaring item that is clearly<br />

visible is that the Mozilla user-agent string says “Gecko”. If you a look at the Opera Mozilla 5.0<br />

disguise, the string does not appear there. Eureka! That makes this easy:<br />

var isMoz = sUserAgent.indexOf(“Gecko”) > -1;<br />

Up until recently, this was enough to determine if the browser was indeed Mozilla. However, as you saw<br />

earlier, KHTML-based browsers have a user-agent string containing the phrase “like Gecko”, which<br />

would also return true for this test. So it is necessary to make sure that the browser contains “Gecko”<br />

but is not KHTML-based:<br />

var isMoz = sUserAgent.indexOf(“Gecko”) > -1<br />

&& !isKHTML;<br />

The isMoz variable is now accurate, so it’s time to move on to the specific versions.<br />

242

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!