同一个链接,PC 访问是 web 应用,而手机打开是一个 H5 应用
文章类型:其他
发布者:hp
发布时间:2025-05-02
有时候我们需要通过一个地址,实现在电脑端和手机端打开,显示不同的效果,那么,怎么实现呢?
(1)前端适配方案(客户端判断)
1:定义:通过JavaScript检测User-Agent进行设备类型判断并跳转
2:代码
// 检测设备类型
const isMobile = /mobile|android|iphone|ipad|phone/i.test(
navigator.userAgent.toLowerCase()
);
// 根据设备类型跳转
window.location.href = isMobile ? '/h5' : '/web';
3:优势:实现简单,无需要后端介入
4:劣势:SEO搜索不友好,有白屏跳转
(2)后端适配方案(服务器判断)
1: Nginx配置
map $http_user_agent $device_type {
default "web";
~*(mobile|android|iphone|ipad) "h5";
}
server {
location / {
try_files /$device_type/index.html =404;
}
}
2:Node.js中间件
const ua = require('express-useragent');
app.use(ua.express());
app.get('/', (req, res) => {
req.useragent.isMobile
? res.sendFile('h5/index.html')
: res.sendFile('web/index.html');
});
优势:无跳转延迟,直接返回内容,对SEO友好
劣势:需要维护设备特征库
1:优先选择后端适配方案,在设备判断准确性、性能与兼容性之间达到平衡