JS|Nuxt 判断是否为手机端|移动端|PC端

in 前端 with 0 comment

原生JS 判断

    const getIsMobile = userAgent => {
        if (
            userAgent.match(/Android/i) ||
            userAgent.match(/webOS/i) ||
            userAgent.match(/iPhone/i) ||
            userAgent.match(/iPad/i) ||
            userAgent.match(/iPod/i) ||
            userAgent.match(/BlackBerry/i) ||
            userAgent.match(/Windows Phone/i)
        )
            return true;
        return false;
    };

    const userAgent = navigator.userAgent;
    const isMobile = getIsMobile(userAgent)
    console.log(isMobile)

Nuxt 判断

asyncData (context) {
    let isMobile = false;
    if (process.server) {
        isMobile = getIsMobile(context.req.headers['user-agent']);
    }
}
Comments are closed.