Can't access window object property in Nuxt (Vue) mounted

8.6k views Asked by At

I have a TronLink chrome extension, this extension provides a window.tronWeb property and I want to access this property after document load. I am trying to do that in the mounted() section of my Nuxt page component:

// ...
mounted() {
  this.tronWeb = window.tronWeb;
},
// ...

but I receive undefined.

I have resolved this problem with a timeout:

// ...
mounted() {
  let _this = this;

  let attempts = 0;
  setTimeout(function startGame() {
    if (window.tronWeb) {
      _this.tronWeb = window.tronWeb;
    } else {
      attempts++;
      if (attempts >= 5) {
        console.log(error);
      } else {
        setTimeout(startGame, 500);
      }
    }
  }, 0);
},
// ...

But it looks like this a very strange solution. Why can't I access this property directly in the mounted() section?

2

There are 2 answers

0
HamidReza Behzadi On

try this:

if (process.browser) {
  console.log('The window object:', window)
}
0
Ahmed Mansour On

you may refer to : nuxt docs > ssr section > window is not defined

because this code is rendered in the server, you can't access the window object.

you may use the process.client to check and run the code only on the client-side

if (process.client){
   console.log('do sth')
}