Chrome's broken back button

Chrome is my primary browser because it’s fast and minimal. One thing surprised me today is its (in)ability to deal with content caches.

The issue I encountered is this.

  • I have a resource myapp.com/my_resource.
  • I first load the page in with a request of content type text/html. The page itself has some Javascript, which will issue an Ajax request to the same URL myapp.com/my_resource. The Ajax request is requesting the same resource URL, but with a different content type, application/json.
  • On the my_resource page, I click on another URL
  • Once I’m on the new page, I hit the back button(I’m lying here, I press the delete key). Chrome dumps out all the JSON data returned by the Ajax request instead of rendering the previous “text/html” page content.

The reason is when Chrome caches content, it discards HTTP headers. This means as long as the resource URL is the same, the Ajax request’s response automatically becomes the cache value for my myapp.com/my_resource URL. To me, this really breaks RESTful web apps’ state management.

Problem is tricky, fix is easy. Just toss in a random number as a postfix to the Ajax request URL (well, it’s not really a solution. The Ajax request will not get cached by the browser anymore…)

$.getJSON "/my_resource?#{new Date().getTime()}", (data) ->
  # blah blah

EDIT

Since I’m working on a Rails app, instead of hacking a timestamp to the Ajax URL, I can just make the URL .json

$.getJSON "/my_resource.json", (data) ->
  # blah blah
Published: 2012-09-03
blog comments powered by Disqus