Refreshing web pages automatically with Play Framework Subscribe Pub Share

During development, it kept bugging me to have to refresh the pages myself to see what I just did and never actually got James Ward's plugin to work properly in my Chrome browser.

... so time to hack. The idea is extremely simple: add a script to the pages which will periodically check with the server and a flag on the server which will indicate if reload is neccessary.

Client code to add to the pages - put in your header template:

@if(isLocalhost) {
  <script type="text/javascript">
  var tstamp = @System.currentTimeMillis();
  var shouldReloadTimer = setInterval(function(){
    $.get("/shouldReload", function( data ) {
      if(data > tstamp) {
        tstamp = data;
        console.log("reloading...");
        location.reload();
      } else {
      }
    }).fail(function(){
      // on error, just backoff for a while
      clearInterval(shouldReloadTimer);
    });
  },2000);
</script>
}

Note that this is inserted in the pages only when running in development mode (localhost) - you need a way to figure out you're on the localhost.

Of course, it requires the awesome jQuery to be in the page, but these days that's not hard.

In your controller, say Application.scala, you simply have to do this:

object Application extends Controller {
  val reloadt=System.currentTimeMillis.toString; // reset when classloader reloads

  // unsecured ping for
  def shouldReload = Action { implicit request =>
        Ok(reloadt).as("application/text") 
    }
}

I'm still using play 2.3 - I understand the controllers are not singletons anymore - so add one.

The flag is reset automatically when play reloads the class loaders, which is right after re-compiling...

Here be dragons

Just did this, so I didn't see any side-effects yet... surely there will be some.

Update:

The first version I had was using a boolean that was reset on the server when reloaded - problematic since that can only reload one page - so if you had a few pages open, only one random page would reload. I updated the code samples here with a time stamp now, so all your open pages will reload.

Update #2

When you recompile with an error - this continuous reload will keep trying and keeps triggering a recompile, heating up the laptop for no reason ;) so I added a check and will disable the reload when there's a problem.

The only issue I noticed with it so far is when using it on edit or form pages - which would reload randomly and often losing the edited content: you may want to disable this auto-reload on these pages.

Enjoy!


Was this useful?    

By: Razie | 2015-06-18 .. 2016-09-06 | Tags: post , scala , play , playframework , programming


See more in: Cool Scala Subscribe

Viewed 7592 times ( | History | Print ) this page.

You need to log in to post a comment!