Ognjen Regoje bio photo

MY NAME IS
Ognjen Regoje
BUT YOU CAN CALL ME OGGY


I make things that run on the web (mostly).
More /ABOUT me.

me@ognjen.io Twitter LinkedIn Github

How to reload the content after the user switches away

In Ooradee, I wanted to have the ability to see updates I made in another window.

The correct way to do this is to implement something like ActionCable. I didn’t want to do this because it’s a lot of work. It’d also require setting up redis.

I wanted to get most of the way there without having to deal with the added complexity.

The approach I took is to listen for when the window gets active once again and to reload the data if it’s older than ten minutes.

First, I added a listener for visibility change on the document in the main Vue app:

document.addEventListener("visibilitychange", this.update)

Once the window visibility changes, the update method checks whether the window is active and has focus. If it does, it triggers an event on the #wrapper element that contains all the html:

update(){
  if (document.visibilityState == "visible" && document.hasFocus()){
    var event = new Event('foregrounded');
    var elem = document.getElementById("wrapper")
    elem.dispatchEvent(event);
  }
}

The components that need to reload the data then listen for that event:

var elem = document.getElementById("wrapper")
elem.addEventListener('foregrounded', this.reload);

And the reload function checks when data was loaded on.

reload(){
  var currentDate = new Date();
  var tenMinutesAgo = new Date(currentDate.getTime() -  10 * 60000);
  if (this.lastLoadedOn == null || this.lastLoadedOn < tenMinutesAgo){
    this.getData()
    this.lastLoadedOn = currentDate;
  }
}

lastLoadedOn set on initial load as well.

So this got me most of the way there with minimal effort.

#actioncable #design #ooradee #visibilitychange