Cookies, JSON, localStorage & Opera

Recently I came across a HTML5 webapp issue where a customer reported that Opera Mobile and Opera Mini were displaying blank pages instead of the actual application. Naturally this required some investigation.

Cookies and JSON

My first thought was to see how the webapp displayed in the Opera desktop browser. It turns out that it had the same issue, where other desktop browsers didn’t. I eventually narrowed it down to a problem with cookies. This particular application uses cookies to save settings that a user can change. It also saves this cookie data in JSON format.

This led to a Twitter conversation between myself and Opera’s Bruce Lawson, in which he asked me to file a bug, which I did. Bruce then followed it up, informing me that Opera doesn’t allow double quotes to be stored in a cookies’ value. This is following the specification (DQUOTE is a special character which can surround the cookie value only) but it appears that other desktop browsers (incorrectly?) allow them regardless. Bruce did say that this behaviour in Opera will change in the future, which is good news. (This does beg the question why the cookie specification isn’t changed to facilitate the storage of JSON data though.)

A partial solution

But it didn’t solve my problem as things still didn’t work in Opera. What else could be used to store such data? HTML5 localStorage of course! So I ammended the code to use localStorage if saving the cookie didn’t work. This then fixed the issues for both desktop Opera and Opera Mobile.

I’m aware that this might seem a backwards solution; having a fallback to HTML5 localStorage rather than the other way around, but a decision was taken earlier on in the project to use cookies instead of localStorage. In hindsight had I known of this cookie issue this decision would probably have been different.

This is a partial solution however as Opera Mini doesn’t support localStorage but should in time support double quotes in cookies.

Potential solutions for Opera Mini

Taking this further, the Opera Mini issue could be solved by saving the JSON data as a simpler string when saving it as a cookie, and then converting it to JSON before use throughout the application. For example, single quotes are acceptable within a cookie value, so all double quotes could be converted to single quotes before saving within the cookie and then converted again on extraction.

Of course all these solutions are temporary, as Bruce mentioned above, future version(s) of Opera should support double quotes in cookies.

Note: if anything in this article is incorrect or you have further information on any of it, please do let me know in the comments below or on Twitter.