Refresh Current Page in JavaScript

It’s more annoying than it sounds. You could do the classic:

window.location = window.location; //refresh lol!

But you’ll get screwed if there is a fragment, like, say, http://example.com/index.html#section1. The page won’t refresh. Or rather, it will, but browsers won’t send a request to the server if the url contains a fragment. It will just try to navigate to that fragment within the document.

Solution: be awesome.

(function(){
  var refreshCookie = "mysite.refreshFragment";

  var refresh = function() {
    var url = window.location.href;
    var fragmentPosition = url.lastIndexOf("#");
    if (fragmentPosition >= 0) {
      if (fragmentPosition !== url.length - 1) {
        $.cookie(refreshCookie, url.substring(fragmentPosition + 1)); //store the fragment in a cookie
      }
      url = url.substring(0, fragmentPosition);
    }
    window.location.href = url;
  };

  var applyFragmentFromCookie = function() {
    var fragment = $.cookie(refreshCookie);
    if (fragment !== null) {
      window.location.href += "#" + fragment;
      $.cookie(refreshCookie, null); //delete cookie
    }
  };

  //reapply the fragment (if necessary) when the page is loaded
  $(document).ready(applyFragmentFromCookie);

  //expose to the public (you would of course properly namespace this, right?)
  window.refresh = refresh;
}());

//then, when you wanted to refresh the page...
refresh();

I use the jQuery cookie plugin, because all the kids nowadays are using jQuery. Substitute your own cookie handling framework, or roll your own (I’ve done it, it’s not enjoyable).

See it in action.

May 9, 2010   Posted in: javascript, web development

2 Responses

  1. Asaph - May 10, 2010

    What about using javascript to dynamically insert a meta refresh tag in the head tag?

  2. tmont - May 10, 2010

    @Asaph – Interesting. Never thought of that. Not sure if a <meta> tag will be picked up dynamically by the browser, though. I’ll give it a try.

    Edit: gave it a try, doesn’t work. Too bad, would’ve been much more elegant.

Leave a Reply