打印浏览器及内核版本
console.log("Browser Information:");
// 获取navigator对象的信息
var userAgent = navigator.userAgent;
console.log("User Agent: ", userAgent);
// 解析User-Agent以获取浏览器信息
var browserInfo = detectBrowser();
console.log(browserInfo);
function detectBrowser() {
var userAgent = navigator.userAgent;
var browser = null;
var version = null;
// 检测浏览器类型
if (userAgent.indexOf("Firefox") > -1) {
browser = "Mozilla Firefox";
version = userAgent.match(/Firefox\/([\d.]+)/)[1];
} else if (userAgent.indexOf("Chrome") > -1) {
browser = "Google Chrome";
version = userAgent.match(/Chrome\/([\d.]+)/)[1];
} else if (userAgent.indexOf("Safari") > -1) {
browser = "Apple Safari";
version = userAgent.match(/Version\/([\d.]+)/)[1];
} else if (userAgent.indexOf("MSIE") > -1 || userAgent.indexOf("Trident/") > -1) {
browser = "Internet Explorer";
// 对于IE11及以上或Edge,使用正则匹配 Trident 字符串后面跟的版本号
version = userAgent.match(/rv:([\d.]+)/)[1];
// Edge 添加单独检测
if (!version && userAgent.indexOf("Edge") > -1) {
browser = "Microsoft Edge";
version = userAgent.match(/Edge\/([\d.]+)/)[1];
}
} else if (userAgent.indexOf("Opera") > -1) {
browser = "Opera";
version = userAgent.match(/Opera\/([\d.]+)/)[1];
}
// 获取浏览器内核信息
var engineInfo = getEngineInfo(userAgent);
console.log("Browser Engine: ", engineInfo.engine, " Version: ", engineInfo.version);
return {
browser: browser,
version: version,
engine: engineInfo.engine,
engineVersion: engineInfo.version
};
function getEngineInfo(ua) {
var engine = 'Unknown';
var version = '';
if (ua.indexOf('WebKit') > -1) {
engine = 'WebKit';
version = ua.match(/WebKit\/([\d.]+)/)[1];
} else if (ua.indexOf('Gecko') > -1) {
engine = 'Gecko';
version = ua.match(/rv:([\d.]+)/)[1];
} else if (ua.indexOf('Presto') > -1) {
engine = 'Presto';
version = ua.match(/Presto\/([\d.]+)/)[1];
} else if (ua.indexOf('Blink') > -1) {
engine = 'Blink';
version = ua.match(/Chrome\/([\d.]+)/)[1]; // Blink 版本通常与Chrome版本一致
}
return { engine, version };
}
}
// 调用检测方法
detectBrowser();