介绍
ua-parser-js
是一个轻量级的 JavaScript 库,用于解析用户代理字符串,以获取有关用户的操作系统、浏览器类型、版本、设备类型等信息。
使用
npm 下载
npm install ua-parser-js
引入
import UAParser from 'ua-parser-js';
const parser = new UAParser('[user-agent]'); // 如果不填写会自动获取当前页面上的ua
const result = parser.getResult();
console.log(result);
返回结果
{
ua: "",
browser: {
name: "",
version: "",
major: "",
type: ""
},
engine: {
name: "",
version: ""
},
os: {
name: "",
version: ""
},
device: {
model: "",
type: "",
vendor: ""
},
cpu: {
architecture: ""
}
}
示例
<style>
* {padding: 0;margin: 0;}
.container {margin: 60px auto;width: 484px;}
#ua {border: 2px solid #f9c645;border-radius: 10px;outline: none;width: 460px;height: 230px;display: block;padding: 10px;font-size: 16px;font-family: 'sans-serif';}
.ua-card div {margin-top: 10px;}
</style>
<div class="container">
<textarea id="ua"></textarea>
<div class="ua-card">
<div>浏览器:</div>
<div>操作系统:</div>
<div>CPU:</div>
<div>引擎:</div>
</div>
</div>
<script src="./ua-parser.min.js"></script>
<script>
const ua = document.getElementById('ua');
const uaCard = document.querySelector('.ua-card');
ua.value = window.navigator.userAgent;
let parser = new UAParser();
let result = parser.getResult();
renderUACard(result)
ua.addEventListener('input', function() {
parser.setUA(ua.value);
result = parser.getResult();
renderUACard(result)
});
function renderUACard(data) {
uaCard.innerHTML = `
<div>浏览器:${data.browser.name}</div>
<div>操作系统:${data.os.name}</div>
<div>CPU:${data.cpu.architecture}</div>
<div>引擎:${data.engine.name}</div>
`;
}
</script>