Wednesday, April 10, 2013

Overcoming the Cookie Size Limit When Using jQuery DataTables and Saved State

One of the features of the jQuery DataTables plugin is that you can use the configuration option "bStateSave" to store the current view of the table (the sort order, the number of rows displayed, the filter term, etc.) in a cookie, so if the user navigates away from the page then comes back, the table view is the same as how they left it.

However, if your website or web application stores the state of several DataTables, and a user hits all those tables faster than those cookies can expire (their default lifespan is 2 hours but can be customized with the "iCookieDuration" option), the user could hit the browser cookie size limit and start seeing errors on your site.  I ran into this problem today with an application I've been working on.

Fortunately, starting with version 1.9, DataTables provides functions that let developers intercept the process of saving the table state and reloading that state, and the plugin author provides a documentation page on how to use those functions to store the state data in localStorage, which in most browsers allows you to store a few MBs of data per site (far more than the 4K limit per site for cookies):

http://datatables.net/blog/localStorage_for_state_saving

In my case, I decided that I would store the state data in sessionStorage rather than localStorage, but the principle was the same.

No comments:

Post a Comment