ブラウザを判別する

説明

ブラウザが独自のプロパティやメソッドを持っているかどうかでブラウザの判別を行います。その後でユーザーエージェントの文字列内にブラウザ固有の文字列が含まれているかどうか調べます。ただし、ユーザーエージェントは必ずしも使用しているブラウザを示しているとは限らないため100%ブラウザを判別できない場合があります。
OS名を調べるにはユーザーエージェント内にOSを示す文字列があるかどうかで判別を行います。OSの判別もブラウザの判別同様にユーザーエージェントが正しいとは限らないため正確に判別できない場合があります。
JavaScriptテクニック ブック  詳しい解説などはJavaScriptテクニック ブックを参照してください。

サンプルコード [実行]

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>JavaScript Sample</title>
<link rel="stylesheet" type="text/css" href="main.css" media="all">
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<h1>ブラウザを判別する</h1>
<form action="./chkbrowser.cgi" method="get" name="mainForm">
<input type="button" id="checkButton" value="ブラウザチェック">
</form>
<div id="result">結果:</div>
</body>
</html>

window.onload = function(){
document.getElementById("checkButton").onclick = function(){
document.getElementById("result").innerHTML = browser.type()+"<br>";
document.getElementById("result").innerHTML += browser.OS();
}
}
var browser = {
type : function(){
if (window.opera) return "Opera";
if (window.createPopup) return "Internet Explorer";
if (navigator.userAgent.indexOf("Safari") > -1) return "Safari";
if (navigator.userAgent.indexOf("Firefox") > -1) return "Firefox";
return "不明";
},
OS : function(){
if (navigator.userAgent.indexOf("Windows") > -1) return "Windows";
if (navigator.userAgent.indexOf("Mac") > -1) return "MacOS";
if (navigator.userAgent.indexOf("X11") > -1) return "Unix";
}
}