mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-03-16 17:10:46 +08:00
feat: improve SSR mobile detection
This commit is contained in:
@@ -1,18 +1,26 @@
|
|||||||
import { ref, computed } from 'vue'
|
import { ref, computed } from 'vue'
|
||||||
|
import { useRequestHeaders } from 'nuxt/app'
|
||||||
|
|
||||||
const width = ref(0)
|
const width = ref(0)
|
||||||
const isClient = ref(false)
|
const isClient = ref(false)
|
||||||
|
|
||||||
// 检测移动设备的用户代理字符串
|
// 检测移动设备的用户代理字符串
|
||||||
const isMobileUserAgent = () => {
|
const isMobileUserAgent = () => {
|
||||||
if (typeof navigator === 'undefined') return false
|
let userAgent = ''
|
||||||
|
|
||||||
const userAgent = navigator.userAgent.toLowerCase()
|
if (typeof navigator !== 'undefined') {
|
||||||
|
userAgent = navigator.userAgent.toLowerCase()
|
||||||
|
} else {
|
||||||
|
// 服务端:从请求头获取用户代理字符串
|
||||||
|
const headers = useRequestHeaders(['user-agent'])
|
||||||
|
userAgent = (headers['user-agent'] || '').toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
const mobileKeywords = [
|
const mobileKeywords = [
|
||||||
'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone',
|
'android', 'iphone', 'ipad', 'ipod', 'blackberry', 'windows phone',
|
||||||
'mobile', 'tablet', 'opera mini', 'iemobile'
|
'mobile', 'tablet', 'opera mini', 'iemobile'
|
||||||
]
|
]
|
||||||
|
|
||||||
return mobileKeywords.some(keyword => userAgent.includes(keyword))
|
return mobileKeywords.some(keyword => userAgent.includes(keyword))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,8 +38,8 @@ export const isMobile = computed(() => {
|
|||||||
if (isClient.value) {
|
if (isClient.value) {
|
||||||
// 客户端:优先使用窗口宽度,如果窗口宽度不可用则使用用户代理
|
// 客户端:优先使用窗口宽度,如果窗口宽度不可用则使用用户代理
|
||||||
return width.value > 0 ? width.value <= 768 : isMobileUserAgent()
|
return width.value > 0 ? width.value <= 768 : isMobileUserAgent()
|
||||||
} else {
|
|
||||||
// 服务端:使用用户代理字符串
|
|
||||||
return isMobileUserAgent()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 服务端:使用请求头中的用户代理字符串
|
||||||
|
return isMobileUserAgent()
|
||||||
})
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user