オブジェクトの有無を調べて、ブラウザの種類とバージョンを判別するスクリプトです。
<html> <head> <title>HTML index Webサイト</title> </head> <body> <script type="text/javascript"> <!-- document.write('<p>ブラウザの判別:'); if(window.opera){ document.write('あなたのブラウザは Opera ですね?'); } else if(document.all){ document.write('あなたのブラウザは Internet Explorer 4〜 ですね?'); } else if(document.getElementById){ document.write('あなたのブラウザは Firefox、または Netscape 6〜 ですね?'); } else if(document.layers){ document.write('あなたのブラウザは Netscape 4 ですね?'); } else{ document.write('判別できませんでした。'); } document.write('</p>'); // --> </script> </body> </html>
特定のオブジェクトに対応しているかどうかを確認して、ブラウザの種類とバージョンを判別する方法です。
上記の例は、window.opera が使える場合は Opera、それ以外で document.all が使える場合は Internet Explorer 4以上、それ以外で document.getElementById が使える場合は Firefox または Netscape 6以上(Safariも?)、最後に document.layers が使える場合は Netscape 4、といった具合にブラウザを判別しています。
青い文字の部分は、必要に応じて書き換えてください。
【対応状況】
IE4 | IE5〜 | Opera | Firefox | NN4 | NN6〜 | |
---|---|---|---|---|---|---|
document.getElementById | × | ○ | ○ | ○ | × | ○ |
document.all | ○ | ○ | ○ | × | × | × |
document.layers | × | × | × | × | ○ | × |
window.opera | × | × | ○ | × | × | × |
上記の対応状況を使って、以下の例のように細かく振分けることもできます。
■IE5以上、Opera、Firefox、NN6以上
if(document.getElementById){ // IE5以上、Opera、Firefox、NN6以上のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■IE4以上、Opera、Firefox、NN6以上
if(document.all || document.getElementById){ // IE4以上、Opera、Firefox、NN6以上のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■FirefoxとNN6以上
if(!document.all && document.getElementById){ // FirefoxとNN6以上のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■IE4以上とOpera
if(document.all){ // IE4以上とOperaのみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■IE4以上
if(document.all && !window.opera){ // IE4以上のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■IE4
if(document.all && !document.getElementById){ // IE4のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■IE5以上とOpera
if(document.all && document.getElementById){ // IE5以上とOperaのみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■Opera
if(window.opera){ // Operaのみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }
■NN4
if(document.layers){ // NN4のみの処理 document.write('<p>結果 ○:処理が実行されました</p>'); } else{ document.write('<p>結果 ×:処理が実行されませんでした</p>'); }