前言
用户代理检测
通过浏览器的用户代理字符串确定使用的是什么浏览器。
JavaScript
中可以通过 navigator.userAgent
访问。
Vue2中用户代理检测
在 Vue2
源码中,有一段用户代理检测。
var inBrowser = typeof window !== 'undefined';
var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform;
var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase();
var UA = inBrowser && window.navigator.userAgent.toLowerCase();
var isIE = UA && /msie|trident/.test(UA);
var isIE9 = UA && UA.indexOf('msie 9.0') > 0;
var isEdge = UA && UA.indexOf('edge/') > 0;
var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android');
var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios');
var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge;
var isPhantomJS = UA && /phantomjs/.test(UA);
var isFF = UA && UA.match(/firefox\/(\d+)/);
这段代码中,Vue2
不关心用户代理是否被篡改,选择相信浏览器返回的用户代理字符串,用来判断浏览器。因为 Vue2
的核心功能不在于 用户代理检测
。
篡改用户代理字符串
console.log(window.navigator.userAgent);
// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36
window.navigator.__defineGetter__('userAgent', () => 'helloworld');
console.log(window.navigator.userAgent);
// helloworld
总结
- 浏览器用户代理字符串可以被篡改。