Nuxt does not have an index. HTML page. Where should we write js code to determine the device
1. Introduce middleware
- in
nuxt.config.js
In addition to therouter
To introducemiddleware
The middleware
nuxt.config.js
The following code
export default {
router: {
middleware: ["device",}}Copy the code
2. Create a directory in the root directoryutils
File and create a new filedeviceType.js
deviceType.js
The file code is as follows
/** ** @param {*} UA, userAgent * @returnstype: device type * env: access environment (wechat/weibo /qq) * masklayer: is to get the external judgment whether to display the masklayer, some special environment to guide the user to the external to open access */function isWechat(UA) {
return /MicroMessenger/i.test(UA) ? true : false;
}
function isWeibo(UA) {
return /Weibo/i.test(UA) ? true : false;
}
function isQQ(UA) {
return /QQ/i.test(UA) ? true : false;
}
function isMoible(UA) {
return /(Android|webOS|iPhone|iPod|tablet|BlackBerry|Mobile)/i.test(UA) ?
true :
false;
}
function isIOS(UA) {
return /iPhone|iPad|iPod/i.test(UA) ? true : false;
}
function isAndroid(UA) {
return /Android/i.test(UA) ? true : false;
}
export function deviceType(UA) {
if (isMoible(UA)) {
if (isIOS(UA)) {
if (isWechat(UA)) {
return {
type: "ios",
env: "wechat",
masklayer: true}; }if (isWeibo(UA)) {
return {
type: "ios",
env: "weibo",
masklayer: true}; }if (isQQ(UA)) {
return {
type: "ios",
env: "qq",
masklayer: true}; }return {
type: "ios"}; }if (isAndroid(UA)) {
if (isWechat(UA)) {
return {
type: "android",
env: "wechat",
masklayer: true}; }if (isWeibo(UA)) {
return {
type: "android",
env: "weibo",
masklayer: true}; }if (isQQ(UA)) {
return {
type: "android",
env: "qq",
masklayer: true}; }return {
type: "android"}; }return {
type: "mobile"}; }else {
return {
type: "pc"}; }}Copy the code
In 3.middleware
adddevice.js
file
device.js
The following code
// @ts-nocheck
import { deviceType } from "~/utils/deviceType";
export default function(context) {
// @ts-ignore
context.userAgent = process.server ?
context.req.headers["user-agent"] : navigator.userAgent; Context.devicetype = deviceType(context.userAgent); // Add a property to the global context to hold the matching information we return. // context.store.mit () context.store.mit (); // context.store.mit ();"SetDeviceType", context.deviceType); // If the UA is not mobile, the processing is done here.. // context.redirect(status, URL) this allows you to redirect to external sitesif (context.deviceType.type === "pc") {
// context.redirect(302,'www.huanjingwuyou.com'//301 is a permanent redirection, if you want to keep changing as the device type changes, please change it to 302}else {
context.redirect(302,'m.huanjingwuyou.com'//301 is a permanent redirection, if you want to keep changing as the device type changes, please change it to 302}}Copy the code
4. Please click the link for basic documentation on NUXT
- Nuxt climb pit