Category : JavaScript

ユーザーエージェントや、ブラウザの判別(特にIE)をしたいときに使うスクリプトをメモ。
IEの7/8だけでどうしても分岐せざるを得ない、って場合とかに便利です。

とりあえずこれ書いとけばOKって感じで使ってます。

※ IE11用の分岐を追記しました

処理

PC or mobile判定、ブラウザ種別判定

// ua判定
var uaObj = {
	uaDevice: 'device-pc',	// PC or mobile判定
	uaBrouser: false		// ブラウザ種別判定
};
uaObj.checkUA = function(){
	var userAgent = navigator.userAgent.toLowerCase();
	var appVersion = navigator.appVersion.toLowerCase();
	// デバイス判定
	if (userAgent.indexOf('iphone') > 0 || userAgent.indexOf('ipod') > 0 || userAgent.indexOf('android') > 0) {
		uaObj.uaDevice = 'device-mobile';
	}
	// ブラウザ判定
	if (userAgent.indexOf('opera') != -1) {
	uaObj.uaBrouser = 'opera';
	} else if (userAgent.indexOf("msie") != -1) {
		if (appVersion.indexOf("msie 6.") != -1) {
			uaObj.uaBrouser = 'ie6';
		} else if (appVersion.indexOf("msie 7.") != -1) {
			uaObj.uaBrouser = 'ie7';
		} else if (appVersion.indexOf("msie 8.") != -1) {
			uaObj.uaBrouser = 'ie8';
		} else if (appVersion.indexOf("msie 9.") != -1) {
			uaObj.uaBrouser = 'ie9';
		} else {
			uaObj.uaBrouser = 'ie';
		}
	} else if (userAgent.indexOf('trident') != -1) {
		uaObj.uaBrouser = 'ie11';
	} else if (userAgent.indexOf('chrome') != -1) {
		uaObj.uaBrouser = 'chrome';
	} else if (userAgent.indexOf('safari') != -1) {
		uaObj.uaBrouser = 'safari';
	} else if (userAgent.indexOf('firefox') != -1) {
		uaObj.uaBrouser = 'firefox';
	} else {
		uaObj.uaBrouser = false;
	}
};

retinaかどうかの判定

// retinaかどうかをチェック
uaObj.checkDisplay = function(){
	uaObj.pixelRatio = window.devicePixelRatio;
};

// uaObj.pixelRatio > 2 の時はretina、といった分岐を書く

ピクセル比の数値についての参考

こちらのサイト様で詳しく解説されています。