// 定义策略类
class BrowserVersionStrategy {
constructor(browserName, versionPattern) {
this.browserName = browserName;
this.versionPattern = versionPattern;
}
getVersion(userAgent) {
const matches = userAgent.match(this.versionPattern);
if (matches) {
return `${this.browserName}/${matches[1]}`;
}
let spareVersion = userAgent.split(' ')[11];
if (spareVersion) {
return spareVersion;
}
return 'Unknown';
}
}
// 定义策略对象
const strategies = [
new BrowserVersionStrategy('Chrome', /Chrome\/([\d.]+)/),
new BrowserVersionStrategy('Firefox', /Firefox\/([\d.]+)/),
new BrowserVersionStrategy('Safari', /Version\/([\d.]+)/),
new BrowserVersionStrategy('Internet Explorer', /(MSIE |rv:)([\d.]+)/),
new BrowserVersionStrategy('Edge', /Edge\/([\d.]+)/),
new BrowserVersionStrategy('Opera', /(Opera|OPR)\/([\d.]+)/)
];
// 获取浏览器版本
function getBrowserVersion() {
const userAgent = navigator.userAgent;
for (const strategy of strategies) {
const version = strategy.getVersion(userAgent);
if (version !== 'Unknown') {
return version.split('/');
}
}
return ['Unknown', 'Unknown'];
}
console.log(getBrowserVersion())
console