hotwired/stimulus

initialize method runs only when browser tab is active?

michelson opened this issue · 2 comments

Hi there, I'm developing a chat application with hotwire and stimulus, and I have a controller that is initialized for every received message, the messages are appended via turbo_streams. The problem is that if the user is not viewing the browser tab the received messages are not connecting with the stimulus controller; at least that is my guess. My other guess is that it could be that the turbo_streams are not updating the DOM if the browser tab is not active and there is some kind of queuing until the browser is active..

Basically, what the stimulus controller does is make a sound whenever the message is received.

Proof, please turn the audio on.
https://github.com/hotwired/stimulus/assets/11976/9ec6c7e2-2e7b-4f70-b79a-6bce550070a3

The controller is something like this:

export default class extends Controller {
  initialize() {
    const dataset = this.element.dataset
      if(dataset.viewerType !== dataset.author ){
        this.playSound();
    }
  }
}

I would appreciate any hints. Thanks.

lb- commented

I don't think this would have anything to do with Stimulus or Turbo, the browser can choose to ignore JS in non-active tabs.

Maybe this is due to Turbo or some other code relying on setInterval/setTimeout to do updates. In which case these will be actively throttled when the tab is inactive.

https://isamatov.com/prevent-timers-stopping-javascript/

iOS Safari will be even more aggressive and completely block some JS if the tab isn't active.

You may need to explore web workers or some other browser API like push events.

I guess we can close this, since it was finally a Turbo problem and is now fixed