2

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?

Dmytro Zarezenko
  • 10,526
  • 11
  • 62
  • 104
  • If this exenstion is executing and adding this variable to windows with delay then timeout look like suitable solution for me. I would just check if nextTick would make any difference. – chojnicki Apr 09 '20 at 22:14
  • Maybe the extension executes its code after the `mounted` function. – l-portet Apr 09 '20 at 22:38

2 Answers2

3

try this:

if (process.browser) {
  console.log('The window object:', window)
}
1

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')
}
Ahmed Mansour
  • 500
  • 4
  • 14