125
125

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javaScriptで対応ブラウザ判定

Last updated at Posted at 2013-08-09

限定したブラウザでのみサイトを表示したい事が多々あると思うので、ブラウザ判別を楽にするコード。
個人的にmsie 6とかmsie 7とか書くのが面倒なので、勝手にie6とかie7という風に省略。

現状、IE系とChrome、Safari、Opera、FireFoxに対応。
それ以外は"unknown"。

※IE11はPreview版での検証(IE11からuserAgentにMSIEが含まれなくなったので、Tridentのバージョンで判別してます)

JavaScript

/**
 *	ブラウザ名を取得
 *	
 *	@return		ブラウザ名(ie6、ie7、ie8、ie9、ie10、ie11、chrome、safari、opera、firefox、unknown)
 *
 */
var getBrowser = function(){
	var ua = window.navigator.userAgent.toLowerCase();
	var ver = window.navigator.appVersion.toLowerCase();
	var name = 'unknown';
	
	if (ua.indexOf("msie") != -1){
		if (ver.indexOf("msie 6.") != -1){
			name = 'ie6';
		}else if (ver.indexOf("msie 7.") != -1){
			name = 'ie7';
		}else if (ver.indexOf("msie 8.") != -1){
			name = 'ie8';
		}else if (ver.indexOf("msie 9.") != -1){
			name = 'ie9';
		}else if (ver.indexOf("msie 10.") != -1){
			name = 'ie10';
		}else{
			name = 'ie';
		}
	}else if(ua.indexOf('trident/7') != -1){
		name = 'ie11';
	}else if (ua.indexOf('chrome') != -1){
		name = 'chrome';
	}else if (ua.indexOf('safari') != -1){
		name = 'safari';
	}else if (ua.indexOf('opera') != -1){
		name = 'opera';
	}else if (ua.indexOf('firefox') != -1){
		name = 'firefox';
	}
	return name;
};


/**
 *	対応ブラウザかどうか判定
 *	
 *	@param	browsers	対応ブラウザ名を配列で渡す(ie6、ie7、ie8、ie9、ie10、ie11、chrome、safari、opera、firefox)
 *	@return				サポートしてるかどうかをtrue/falseで返す
 *
 */
var isSupported = function(browsers){
	var thusBrowser = getBrowser();
	for(var i=0; i<browsers.length; i++){
		if(browsers[i] == thusBrowser){
			return true;
			exit;
		}
	}
	return false;
};

// テストコード(chrome、safari、opera、firefox、ie11だとtrueが、その他だとfalseが返る)
alert(isSupported(['chrome','safari','opera','firefox','ie11']));

125
125
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
125
125

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?