David M. Karr
David M. Karr

Reputation: 15225

How to do "meta refresh", but only if the page exists

I have a simple SPA used by our team, using angular1. It gets most of its data from REST calls, but I also have a "meta refresh" tag to occasionally reload the whole page, to make sure the user gets occasional small functionality changes. There is no need to ever make this optional, it should just reload the page.

The minor annoyance with this strategy is that when the user sometimes disconnects from the network (traveling between work and home, for instance), the page reload fails, and it gets into an error state. It's easy enough to just force reload the page, but I'd like for this to be a little cleaner, such that it only reloads the page if it can reach the page.

I noticed the advice at https://davidwalsh.name/meta-refresh-javascript . That uses javascript to do the reload, but it's not conditional on the page existing.

Is there a reasonable variation of this that will simply skip the reload when it can't reach the page, and then reload again when it can?

Upvotes: 0

Views: 193

Answers (2)

David M. Karr
David M. Karr

Reputation: 15225

For my needs, I ended up implementing a "heartbeat" method in my controller, which calls a Heartbeat service, which does a HEAD request to my REST service, and returns true if the status is 200.

I then call this from the HTML like this:

<script type="text/javascript">
    window.setInterval(function() {
        // Call controller method to call heartbeat service.
        if (angular.element(document.body).scope().heartbeat()) {
            window.location.reload();
        }
    }, 900000)
</script>

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

The navigator object has a property online that you could check

if(window.navigator.online){
  window.location.reload(); 
}

Or make an ajax head request first and if that succeeds do the refresh

Upvotes: 1

Related Questions