Last Updated: February 25, 2016
·
777
· gapple

Fix AJAX requests failing after navigating back in Safari

Drupal and many other systems use a unique token on forms to prevent CSRF attacks.

After ensuring that the correct Cache-Control headers were set, and that Safari was indeed making a fresh request to the server to get the updated form, Safari still seemed to be sending an outdated token with AJAX requests after navigating back in the browser, causing them to fail.

The issue seems to be with Safari re-populating the form data for hidden fields, and can be resolved by setting the autocomplete attribute on the field that holds the CSRF token:

Drupal.behaviors.safariBackAjaxFix = {
  attach: function (context, settings) {
    /**
     * Fix for AJAX requests failing after hitting the back button in Safari.
     * Without autocomplete disabled on the hidden form_build_id input,
     * Safari resets the form state when navigating back, ignoring the fresh
     * form_build_id it needs and using the old one that no longer works.
     */
    $('input[name="form_build_id"]').attr('autocomplete', 'off');
  }
};

Afterwards, Safari respects the updated token in the input and AJAX requests are successful.