Search code examples
webkitbrowser-historypjaxpopstate

PJAX: Problems with back button


Some our links are wrapped by PJAX. When a user clicks on a PJAX link the server returns only the required part of the HTML.

If I do the following:

  1. Click PJAX link
  2. Click simple link
  3. Press back button

the browser will display content that was returned by the PJAX request. The HTML will be broken because it's only part of the HTML to be displayed (check this question).

We have tried to fix this by not caching PJAX responses (Cache-Control header). This fixed our problem but raised another one: When the user presses the back button, WebKit (Chrome 20.0) loads full content from server, then fires popstate event that causes an unnecessary PJAX request.

Is it possible to recreate correct back button behaviour?


Solution

  • This all depends from server caching settings. You browser caches the AJAX response from server and when you click Back button it uses cached version.

    To prevent caching set following headers on server:

    'Cache-Control' => 'no-cache, no-store, max-age=0, must-revalidate'
    'Pragma' => 'no-cache'
    

    If you are using Rails, then definitely try Wiselinks https://github.com/igor-alexandrov/wiselinks. It is a a Swiss Army knife for browser state management. Here are some details: http://igor-alexandrov.github.io/blog/2013/07/11/the-way-to-wiselinks-1-dot-0/.