美文网首页
H5判断移动设备的型号和浏览器

H5判断移动设备的型号和浏览器

作者: ThemisHoo | 来源:发表于2019-11-28 17:22 被阅读0次
    实际上 navigator.userAgent 就可以拿到所有信息

    Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Mobile Safari/537.36

    我们需要分离出具体的手机型号和浏览器就要做一些解析

    首先安装mobile-detect
    npm install mobile-detect --save
    
    在node中使用mobile-detect

    (我尝试在前端页面使用import MobileDetect from 'mobile-detect',但md = new MobileDetect(detectType)打印出的结果为null,不知道是哪里写错了,还是不支持import)

    const MobileDetect = require('mobile-detect');
    
    exports.requestMapping = '/verify';
    
    Array.prototype.contains = (needle) => {
        for (i in this) {
            if(this[i].indexOf(needle) > 0) {
                return i
            }
            return -1
        }
    }
    // 增加埋点
    router.post('/detect_type', (req, res, next) => {
        let detectType = req.body.detectType
        let md = new MobileDetect(detectType)
        console.log(detectType)
        console.log(md)
        let os = md.os() // 获取系统
        let model = md.mobile()
        if(os == 'iOS') {
            os = `${md.os()}${md.version("iPhone")}`
            model = md.mobile()
        }else if(os == 'AndroidOS') {
            os = `${md.os()}${md.version("Android")}`
            let sss = detectType.split(';')
            let i = sss.contains("Build/")
            if(i > -1) {
                model = sss[i].substring(0, sss[i].indexOf("Build/"))
            }
        }
        LOG.info(`系统:${os}---手机型号:${model}---浏览器:${md.userAgent()}`)
        res.json({success: true,data: `${os}---${model}`});
    });
    

    这里md打印出的信息为

    MobileDetect {
    ua: 'Mozilla/5.0 (Linux; Android 8.0.0; Nexus 6P Build/OPP3.170518.006) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Mobile Safari/537.36',
    _cache: {},

    maxPhoneWidth: 600 }

    在前端中调用detect_type传入navigator.userAgent
            let detect_type = window.navigator.userAgent
            let data = {
                detectType: detect_type
            }
            this.request.post('/verify/detect_type', data).then((res)=> {
                console.log(res)
            }).catch()
    

    参考文档:https://github.com/hgoebl/mobile-detect.js/
    参考文档:https://www.jb51.net/article/136197.htm

    相关文章

      网友评论

          本文标题:H5判断移动设备的型号和浏览器

          本文链接:https://www.haomeiwen.com/subject/tjlbwctx.html