最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Set Cookie with Javascript and sanitize value - Stack Overflow

programmeradmin3浏览0评论

I need to set a cookie with javascript which I'm doing this with the following mand:

document.cookie = name+"="+value;

My problem is that value is a string, which can contain any unicode-character.

Is there a function which automatically replaces special characters (like ;) - and if not, which characters are forbidden?

Something like the "encodeURIComponent()"-Function for Get-Parameters would be perfect

I need to set a cookie with javascript which I'm doing this with the following mand:

document.cookie = name+"="+value;

My problem is that value is a string, which can contain any unicode-character.

Is there a function which automatically replaces special characters (like ;) - and if not, which characters are forbidden?

Something like the "encodeURIComponent()"-Function for Get-Parameters would be perfect

Share Improve this question edited Sep 9, 2014 at 14:36 maja asked Jun 27, 2012 at 17:19 majamaja 18.1k18 gold badges84 silver badges127 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

You should use window.escape.

The escape() method converts special characters (any characters that are not regular text or numbers) into hexadecimal characters, which is especially necessary for setting the values of cookies. Also useful when passing name=value pairs in the URL of a GET request, or an AJAX GET/POST request.

It also has window.unescape counterpart.

Upd. It may make some sense to use base64 encoding/decoding prior to escaping in order not to suffer that much from unicode characters expenditure by window.encode.

Why not use a robust cookie library to handle cookies?

$.cookie('key', value, { expires: 365 });

Browsers limit cookies to 4 kB. If you need to store more than 4 kB on the client, you should use local storage.

发布评论

评论列表(0)

  1. 暂无评论