Data Storage In User Cookie
When user interface elements such as
Twisty store their settings in persistent cookies, the limit of 20 cookies per domain is reached soon (see
cookie specification).
This topic describes the method Foswiki uses to overcome this limit, and how to read and write preference values in an easy and consistent way.
Reading and writing settings
To limit the number of cookies, Foswiki reads and writes settings to one cookie named
FOSWIKIPREF
, to be shared amongst core and plugins.
pub/JavascriptFiles/foswikiPref.js
has 2 functions to write data to and read data from a user cookie:
-
foswiki.Pref.setPref(inPrefName, inPrefValue)
writes a preference value with name inPrefName
and value inPrefValue
-
foswiki.Pref.getPref(inPrefName)
reads a preference value with name inPrefName
Any value string can be set, with the exception of characters
|
(pipe) and
=
(equals) that are reserved as delimiters. Reserved characters are stripped from preference names and values.
Technically, all preferences written to FOSWIKIPREF are concatenated to one long string, each a key-value pair:
FOSWIKIPREF = |SHOWATTACHMENTS=1|SHOWFORM=1|somepref=somevalue
The size limit for one cookie is 4KB - for storing preference values this will presumably suffice.
Usage
Writing a preference
<script language="javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiPref.js"></script>
<script type="text/javascript">
foswiki.Pref.setPref('SHOWATTACHMENTS', '1');
</script>
If you write a cookie from a plugin or contrib javascript, add the plugin name:
<script language="javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiPref.js"></script>
<script type="text/javascript">
var prefName = "MyPlugin" + "MYSETTING";
var prefValue = "on";
foswiki.Pref.setPref(prefName, prefValue);
</script>
Reading a preference
<script language="javascript" src="%PUBURL%/%SYSTEMWEB%/JavascriptFiles/foswikiPref.js"></script>
<script type="text/javascript">
var doShow = foswiki.Pref.getPref("SHOWATTACHMENTS");
</script>
Foswiki's session management also uses a cookie (FOSWIKISID). This cookie identifies a unique session ID that is then used as the lookup key for all the other session-specific values Foswiki uses.
An alternative approach would be to use a Rest script on the server to serve this session-specific information on demand. This would allow one to escape the 4KB limit, but would inevitably be slower (and only available if sessions are active).
More info
Links:
Contributors:
ArthurClemens,
CrawfordCurrie