var user = navigator.userAgent;
var browser = {};
browser.opera = user.indexOf("Opera") > -1 && typeof window.opera == "object";
browser.khtml = (user.indexOf("KHTML") > -1 || user.indexOf("AppleWebKit") > -1 || user.indexOf("Konqueror") > -1) && !browser.opera;
browser.ie = user.indexOf("MSIE") > -1 && !browser.opera;
browser.gecko = user.indexOf("Gecko") > -1 && !browser.khtml;
if ( browser.ie ) {
var ie_reg = /MSIE (\d+\.\d+);/;
ie_reg.test(user);
var v = parseFloat(RegExp["$1"]);
browser.ie55 = v <= 5.5;
browser.ie6 = v <= 6;
}
Recently, I am leaning JavaScript. I saw some code to check the browser, but I can't follow it well. The code is too hard for me. Can explain it to me? Many thanks.
navigator.userAgent
contains a String with data about the current browser.
In the second line of code you create a browser
object which is empty. Then, you add properties which are either true
or false
depending on the browser. For example, if the browser is Opera, the word Opera
is somewhere in navigator.userAgent
. The same appearently is done for KHTML and Gecko.
To actually check whether a String contains some characters/words, you can use indexOf
. This will return the index at which the word starts. If it doesn't appear in the String, it returns -1. So checking for > -1
means checking whether it contains the word.
When it comes to IE, you can differ between version 5.5 and version 6 by executing a regular expression on navigator.userAgent
. This is a kind of shape you place on the string to filter out what you need. You check whether the version parsed out is 5.5 or is 6 and store that data appropriately.
So in the end the browser
object contains values on which browser is being used.
精彩评论