getRecoverableString
This script can serialise strings, numbers, boolean values, regular expressions, date objects, and even objects, arrays, and functions into a valid string. This can then be saved into a cookie (*), or evaluated back into a valid variable, replicating the original variable structure. There are a few limitations;
- DOM nodes are not serialised (represented as {error:'DOM node'} or {error:'internal object'})
- Arrays can either have indexes, or key/values, not both
- Arrays using only key/values are represented as objects
- Cyclic references are not allowed, and will be automatically removed (represented as ['LoopBack'] or {'LoopBack'})
- Internal functions cannot be referenced (represented as function () {['native code']})
- Using numeric strings ('00') as object property names is not possible (they will be treated as numbers)
- Safari will corrupt big functions
That said, it is a very complete representation and can be used to store and recover a substantial number of data types and formats.
* Although the script attempts to be efficient with its storage of variables, cookies are limited to 4 KB of escaped data, and this will limit the amount of serialised data that you can reliably store in a cookie.
To download the script(s), see the script license, and check details like browser compatibility, use the links on the navigation panel at the top of this page.
Sample output
The following is a sample of a complicated variable structure, that this script is able to serialise - see the source code for more details of what it is serialising:
Warning
Recovering the string makes use of the eval method. You should never eval code if you do not know if it is safe. Only eval code that you have created yourself, or at most is stored in a cookie. Using eval on code passed as a variable in the address, or via forums or POST methods will result in allowing cross-site scripting attacks.