简体   繁体   中英

Set Cookie with Javascript and sanitize value

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

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

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 .

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM