JS判断手机浏览器操作系统及微信浏览器的方法

作者:像素猫时间:2026-10-31 00:17:55浏览:541

本文介绍利用JavaScript判断客户端平台及系统平台的方法。通过navigator.userAgent属性,可以识别Android、iOS、Linux等操作系统,并进一步检测是否为微信内置浏览器。文中提供了基于jQuery的完整示例代码,展示了如何获取平台信息并输出对应结果,适用于移动端网页开发中的环境检测场景。

JS判断手机浏览器操作系统及微信浏览器的方法

本文将介绍如何使用JavaScript来识别客户端的平台类型以及操作系统的具体信息。


<script type="text/javascript">
//手机端判断各个平台浏览器及操作系统平台
function checkPlatform(){
	if(/android/i.test(navigator.userAgent)){
		document.write("This is Android'browser.");//这是Android平台下浏览器
	}
	if(/(iPhoneiPadiPodiOS)/i.test(navigator.userAgent)){
		document.write("This is iOS'browser.");//这是iOS平台下浏览器
	}
	if(/Linux/i.test(navigator.userAgent)){
		document.write("This is Linux'browser.");//这是Linux平台下浏览器
	}
	if(/Linux/i.test(navigator.platform)){
		document.write("This is Linux operating system.");//这是Linux操作系统平台
	}
	if(/MicroMessenger/i.test(navigator.userAgent)){
		document.write("This is MicroMessenger'browser.");//这是微信平台下浏览器
	}
}
 $(document).ready(function(){
  alert(navigator.platform);
  checkPlatform();
 });
</script>

上述代码示例依赖于jQuery库,因此在使用前必须确保页面已加载jQuery。如果不需要特定的触发逻辑,可以直接移除相关的函数调用部分。

本文暂不深入探讨PC端操作系统的判断细节,但简要说明其原理:通过执行document.write(navigator.platform)可以获取操作系统平台的标识。例如,在Windows 32位系统下会显示Win32,而在64位系统下则显示Win64。

接下来,本文将补充几个实用的检测函数,以增强平台识别的准确性。


<script type="text/javascript">
var browser = {
	versions : function () {
		var u = navigator.userAgent,
		app = navigator.appVersion;
		return {
			trident : u.indexOf('Trident') > -1,
			presto : u.indexOf('Presto') > -1,
			webKit : u.indexOf('AppleWebKit') > -1,
			gecko : u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
			mobile : !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
			ios : !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
			android : u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
			iPhone : u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1,
			iPad : u.indexOf('iPad') > -1,
			webApp : u.indexOf('Safari') == -1,
			QQbrw : u.indexOf('MQQBrowser') > -1,
			weiXin : u.indexOf('MicroMessenger') > -1,
			ucLowEnd : u.indexOf('UCWEB7.') > -1,
			ucSpecial : u.indexOf('rv:1.2.3.4') > -1,
			ucweb : function () {
				try {
					return parseFloat(u.match(/ucweb\d+\.\d+/gi).toString().match(/\d+\.\d+/).toString()) >= 8.2
				} catch (e) {
					if (u.indexOf('UC') > -1) {
						return true;
					} else {
						return false;
					}
				}
			}
			(),
			Symbian : u.indexOf('Symbian') > -1,
			ucSB : u.indexOf('Firefox/1.') > -1
		};
	}
	()
}
if (browser.versions.QQbrw){
document.write("qq浏览器");
}else
{
document.write("其它浏览器");
}
</script>

经实际测试,这些方法效果良好,具有较高的实用性。

作者最新文章