我们同一个网页,可能会在pc端打开或者不同的移动端打开,那么,我们想要在不同的设备上打开显示不同的效果,就需要知道当前是以什么方式打开的浏览器。navigator对象提供的属性可以解决这些问题,navigator对象包含有关浏览器的信息。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>浏览器</title>
</head>
<body>
</body>
<script>
var browser = {
versions: function () {
var u = navigator.useragent, app = navigator.appversion;
return { //移动终端浏览器版本信息
trident: u.indexof('trident') > -1, //ie内核
presto: u.indexof('presto') > -1, //opera内核
webkit: u.indexof('applewebkit') > -1, //苹果、谷歌内核
gecko: u.indexof('gecko') > -1 && u.indexof('khtml') == -1, //火狐内核
mobile: !!u.match(/applewebkit.*mobile.*/), //是否为移动终端
ios: !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/), //ios终端
android: u.indexof('android') > -1 || u.indexof('linux') > -1, //android终端或uc浏览器
iphone: u.indexof('iphone') > -1, //是否为iphone或者qqhd浏览器
ipad: u.indexof('ipad') > -1, //是否ipad
webapp: u.indexof('safari') == -1 //是否web应该程序,没有头部与底部
};
}(),
language: (navigator.browserlanguage || navigator.language).tolowercase()
};
if (browser.versions.mobile) {//判断是否是移动设备打开。browser代码在下面
var ua = navigator.useragent.tolowercase();//获取判断用的对象
// alert('是在移动端打开');
if (ua.match(/micromessenger/i) == "micromessenger") {
//在微信中打开
alert('在微信中打开');
}
if (ua.match(/weibo/i) == "weibo") {
在新浪微博客户端打开
}
if (ua.match(/qq/i) == "qq") {
//在qq空间打开
alert('在qq打开的');
}
if (browser.versions.ios) {
//是否在ios浏览器打开
alert('是在ios浏览器打开');
}
if(browser.versions.android){
//是否在安卓浏览器打开
alert('是在安卓浏览器打开');
}
} else {
//否则就是pc浏览器打开
alert('是在pc端打开的');
}
</script>
</html>
以上就是js判断当前打开浏览器的方式的详细内容。