Fix navigator/window/document undefined method in Nuxt
P粉143640496
P粉143640496 2024-03-25 19:00:40
0
1
383

I'm trying to determine the UserAgent and Retina information within a Nuxt application. But the application throws an error and says navigation/window is undefined. How do I get this information in a nuxt application?

const userAgent = navigator.userAgent.toLowerCase()
const isAndroid = userAgent.includes('android')
isRetina() {
  let mediaQuery
  if (typeof window !== 'undefined' && window !== null) {
    mediaQuery =
      '(-webkit-min-device-pixel-ratio: 1.25), (min--moz-device-pixel-ratio: 1.25), (-o-min-device-pixel-ratio: 5/4), (min-resolution: 1.25dppx)'
    if (window.devicePixelRatio > 1.25) {
      return true
    }
    if (window.matchMedia && window.matchMedia(mediaQuery).matches) {
      return true
    }
  }
  return false
}

P粉143640496
P粉143640496

reply all(1)
P粉242126786

This is the solution to fix:

  • navigator undefined
  • window undefined
  • Document not defined

This is an example on how to wrap logical JS code

sssccc

As shown below: https://nuxtjs.org/docs/2. x/internals-glossary/context

PS: mounted process.client is a bit redundant, because mounted only runs on the client.


Also, if you want the component to be rendered only on the client side, it is also a good idea to wrap the component in <client-only>.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!