在瀏覽器百家爭鳴的年代,同一份網頁常得為 Netscape、IE、Opera、WebTV、AOL 等各自準備不同版本。這段經典的 browserSniffer 函式,會讀取 navigator.userAgent 與 appVersion,判斷使用者所用的瀏覽器與版本,再自動把視窗導向該瀏覽器專屬的頁面,是早期「一頁多版」策略的常見做法。
函式透過一連串布林變數(如 is_nav4up、is_ie4up、is_opera、is_webtv 等)比對 user-agent 字串,最後依序用 location.href 導到不同網址。只要在 <body> 的 onLoad 呼叫它並傳入各版本的網址即可。
<SCRIPT language="JavaScript">
<!--
function browserSniffer(netscape4URL, explorer4URL, webtvURL, aolURL, operaURL, version3URL, w3cURL) {
var agt = navigator.userAgent.toLowerCase();
var is_major = parseInt(navigator.appVersion);
var is_nav = ((agt.indexOf('mozilla') != -1) && (agt.indexOf('spoofer') == -1)
&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera') == -1)
&& (agt.indexOf('webtv') == -1));
var is_nav4up = (is_nav && (is_major >= 4));
var is_nav5up = (is_nav && (is_major >= 5));
var is_ie = (agt.indexOf("msie") != -1);
var is_ie3 = (is_ie && (is_major < 4));
var is_ie4up = (is_ie && (is_major >= 4));
var is_aol = (agt.indexOf("aol") != -1);
var is_opera = (agt.indexOf("opera") != -1);
var is_webtv = (agt.indexOf("webtv") != -1);
if (is_nav5up) {
location.href = w3cURL; // Netscape 5 以上
} else if (is_nav4up) {
location.href = netscape4URL; // Netscape 4.x
} else if (is_ie4up) {
location.href = explorer4URL; // IE4 以上
} else if (is_webtv) {
location.href = webtvURL; // WebTV
} else if (is_aol) {
location.href = aolURL; // AOL
} else if (is_opera) {
location.href = operaURL; // Opera
} else if (is_ie3) {
location.href = version3URL; // 3.0 等舊版
}
}
//-->
</SCRIPT>
<BODY onLoad="browserSniffer('nn4.html','IE4.html','webtv.html','aol.html','Opera.html','ver3.html','nn6.html')">
現今已不太需要靠 user-agent 判斷來切換整頁,主流做法是採用「功能偵測」與響應式設計(RWD),讓同一份內容依裝置自動排版,維護起來更單純也更可靠。