Getting DataTables to keep its state when the user clicks the back button (without the stateSave option)

Nick picture Nick · Nov 11, 2016 · Viewed 13.1k times · Source

The problem I'm experiencing in Chrome and Edge:

  1. Go to https://datatables.net/examples/basic_init/zero_configuration.html
  2. Sort the table by some column (e.g. "Age")
  3. Use the pagination interface at the bottom of the table to go to one of the other pages
  4. Click on one of the navigation links to the left (e.g. "FAQs" or "Download")
  5. Click the browser's back button and observe that the table is now back to its original state (sorted by the "Name" column and on page 1)

In Firefox, the table is still sorted by the correct column and is still on the correct page. How can I make Chrome and Edge also behave this way?

I know DataTables has its stateSave option (documentation and example), but the problem with that is when the user navigates around the site and then clicks a link to go to the page that has the DataTables table, it will put them back into the same state in that scenario too. I only want the user to be put back into the same state if they use their browser's back button.

Answer

Dex Dave picture Dex Dave · Nov 17, 2016

Based on this post you could clear the saved state when you click on the link that leads you to the page with the table

see example here

$(document).ready(function() {
    $('#example').DataTable( {
        "paging":   true,
        "ordering": true,
        "info":     false,
        stateSave: true
    } );
} );

$(".table_link").on("click", function(){
  $('#example').DataTable().state.clear();
});