18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Browser and Operating System Detection<br />

var reApple<strong>Web</strong>Kit = new RegExp(“Apple<strong>Web</strong>Kit\\/(\\d+(?:\\.\\d*)?)”);<br />

reApple<strong>Web</strong>Kit.test(sUserAgent);<br />

var fApple<strong>Web</strong>KitVersion = parseFloat(RegExp[“$1”]);<br />

isMinSafari1 = fApple<strong>Web</strong>KitVersion >= 85;<br />

isMinSafari1_2 = fApple<strong>Web</strong>KitVersion >= 124;<br />

} else if (isKonq) {<br />

}<br />

}<br />

var reKonq = new RegExp(“Konqueror\\/(\\d+(?:\\.\\d+(?:\\.\\d)?)?)”);<br />

reKonq.test(sUserAgent);<br />

isMinKonq2_2 = compareVersions(RegExp[“$1”], “2.2”) >= 0;<br />

isMinKonq3 = compareVersions(RegExp[“$1”], “3.0”) >= 0;<br />

isMinKonq3_1 = compareVersions(RegExp[“$1”], “3.1”) >= 0;<br />

isMinKonq3_2 = compareVersions(RegExp[“$1”], “3.2”) >= 0;<br />

In this section of the code, check whether the compareVersions() returns a value greater-than or equal<br />

to zero, which indicates that the versions are either equal (if it returns 0) or that the first version is<br />

greater than the second (if it returns 1).<br />

The detection for KHTML-based browsers is complete. You can either just use isKHTML if you don’t care<br />

which browser is being used, or use the more specific variables to determine the browser and version.<br />

Detecting Internet Explorer<br />

As discussed earlier, the IE user-agent string is quite unique. Recall the user-agent string for IE 6.0:<br />

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT)<br />

When you compare this to other browsers, two parts stand out as unique: “compatible” and “MSIE”.<br />

This is the basis for detecting IE:<br />

var isIE = sUserAgent.indexOf(“compatible”) > -1<br />

&& sUserAgent.indexOf(“MSIE”) > -1;<br />

This seems to be straightforward, but there is a problem. Take a second look at the Opera user-agent<br />

string when it is disguised as IE 6.0:<br />

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Opera 7.54<br />

See the problem? If you check for only “compatible” and “MSIE”, then Opera disguised as IE also returns<br />

true. The solution is to use the isOpera variable (explained previously) to ensure proper detection:<br />

var isIE = sUserAgent.indexOf(“compatible”) > -1<br />

&& sUserAgent.indexOf(“MSIE”) > -1<br />

&& !isOpera;<br />

Next, define variables for the different IE versions:<br />

var isMinIE4 = isMinIE5 = isMinIE5_5 = isMinIE6 = false;<br />

241

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

Saved successfully!

Ooh no, something went wrong!