JSON.parse Fails in Safari when a string value contains a comma

Okay, now we've got to the root of the actual problem, I think I can help.

The problem is basically that you're storing data into the cookie string but not escaping it. So when you set the cookie and it contains commas, the commas can be seen as cookie delimiters. For most of your string, the quotes in the JSON seem to be masking this effect (quotes are also relevant characters for cookies), but for this one it is being seen by the cookie parser as a delimiter.

This in turn means that it is seen as the end of the cookie, which means when you load it back it is truncated at that point.

Solution: Escape the string before saving it as a cookie. (your makeCookie() function should do this). You should be able to use the JS escape() function for this.

See the cookie spec, and note that commas, double quotes, semi-colons, and more are relevant characters for cookies.

See also: this similar issue

As for why it's happening in Safari and not other browsers... I guess that's probably down to luck as much as anything else. Maybe the other browsers' cookie parsers recognise that the following string after the comma isn't valid and thus work out that the comma isn't intended as a delimiter.

You might also want to see the MDN cookie article which includes code for a sample JS coookie library, which does do all the proper escaping. You may want to consider using this lib instead of your own current code. (or at least parts of it)

Hope that helps.

Finally, slightly off topic, but one additional thing to be aware of when using cookies: Don't forget that the entire cookie string is transmitted in both directions for every single http request made on your site. So if you've got 4k of cookie data, that means an additional 8k of bandwidth for every html, css, js and image file on your site.

If you're using large cookies, there are alternative ways to store local data which are not subject to this problem. This article might be helpful for you.