No longer maintained, superseded by JS Cookie:

Overview

IMPORTANT!

This project was moved to https://github.com/js-cookie/js-cookie, check the discussion.

New issues should be opened at https://github.com/js-cookie/js-cookie/issues

jquery.cookie Build Status Code Climate

A simple, lightweight jQuery plugin for reading, writing and deleting cookies.

If you're viewing this, you're reading the documentation for the old repository. View documentation for the latest backwards compatible release (1.5.1).

Build Status Matrix

Selenium Test Status

Installation

Include script after the jQuery library (unless you are packaging scripts somehow else):

<script src="/path/to/jquery.cookie.js"></script>

Do not include the script directly from GitHub (http://raw.github.com/...). The file is being served as text/plain and as such being blocked in Internet Explorer on Windows 7 for instance (because of the wrong MIME type). Bottom line: GitHub is not a CDN.

The plugin can also be loaded as AMD or CommonJS module.

Usage

Create session cookie:

$.cookie('name', 'value');

Create expiring cookie, 7 days from then:

$.cookie('name', 'value', { expires: 7 });

Create expiring cookie, valid across entire site:

$.cookie('name', 'value', { expires: 7, path: '/' });

Read cookie:

$.cookie('name'); // => "value"
$.cookie('nothing'); // => undefined

Read all available cookies:

$.cookie(); // => { "name": "value" }

Delete cookie:

// Returns true when cookie was successfully deleted, otherwise false
$.removeCookie('name'); // => true
$.removeCookie('nothing'); // => false

// Need to use the same attributes (path, domain) as what the cookie was written with
$.cookie('name', 'value', { path: '/' });
// This won't work!
$.removeCookie('name'); // => false
// This will work!
$.removeCookie('name', { path: '/' }); // => true

Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is.

Configuration

raw

By default the cookie value is encoded/decoded when writing/reading, using encodeURIComponent/decodeURIComponent. Bypass this by setting raw to true:

$.cookie.raw = true;

json

Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:

$.cookie.json = true;

Cookie Options

Cookie attributes can be set globally by setting properties of the $.cookie.defaults object or individually for each call to $.cookie() by passing a plain object to the options argument. Per-call options override the default options.

expires

expires: 365

Define lifetime of the cookie. Value can be a Number which will be interpreted as days from time of creation or a Date object. If omitted, the cookie becomes a session cookie.

path

path: '/'

Define the path where the cookie is valid. By default the path of the cookie is the path of the page where the cookie was created (standard browser behavior). If you want to make it available for instance across the entire domain use path: '/'. Default: path of page where the cookie was created.

Note regarding Internet Explorer:

Due to an obscure bug in the underlying WinINET InternetGetCookie implementation, IE’s document.cookie will not return a cookie if it was set with a path attribute containing a filename.

(From Internet Explorer Cookie Internals (FAQ))

This means one cannot set a path using path: window.location.pathname in case such pathname contains a filename like so: /check.html (or at least, such cookie cannot be read correctly).

domain

domain: 'example.com'

Define the domain where the cookie is valid. Default: domain of page where the cookie was created.

secure

secure: true

If true, the cookie transmission requires a secure protocol (https). Default: false.

Converters

Provide a conversion function as optional last argument for reading, in order to change the cookie's value to a different representation on the fly.

Example for parsing a value into a number:

$.cookie('foo', '42');
$.cookie('foo', Number); // => 42

Dealing with cookies that have been encoded using escape (3rd party cookies):

$.cookie.raw = true;
$.cookie('foo', unescape);

You can pass an arbitrary conversion function.

Contributing

Check out the Contributing Guidelines

Authors

Klaus Hartl

Comments
  • Not possible to set expire to non-integer count of days

    Not possible to set expire to non-integer count of days

    In my task I need expire period half-hour. Half hour recalculated in days is 1 / 48.

    But this doesn't work. Because the result expiration is counted in that way:

    if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDays(t.getDays() + days); }

    Function setDays understands only integers. The solution is very simple: t.setSeconds(t.getSeconds() + days * 24 * 60 * 60);

    In that way it will work.

    bug 
    opened by Stalinko 28
  • Remove jQuery dependency requirement?

    Remove jQuery dependency requirement?

    The plugin internals does not rely that much on jQuery and semantically it doesn't make much sense, jQuery is a library created only to manipulate the DOM, the same is expected from its plugins.

    Maybe at the time it made sense using jquery namespace to prevent globals cluttering, since everyone were including it, but today there are many applications that don't need jQuery at all, and in some cases having jQuery as a dependency is more a burden than a benefit.

    I am not saying to remove jQuery dependency, that can't happen due to historical reasons. What I am saying is that, considering the actual tendency of using MV* frameworks like angular and the (slow but ongoing) official specs, one could think about using jquery-cookie being jquery an optional dependency.

    The intent is to leverage an existent plugin to fit additional use cases, or make it easy to do so. angular cookie, for example, doesn't let ppl provide additional options to the cookie. A limitation already addressed by jquery cookie a long time ago.

    It would be useful to expose a decent api to integrate easily with angular and other tools that doesn't rely exclusively on jquery.

    The idea would be to do something like this for v2, since it means a break in backwards compatibility (a new namespace will break existing code).

    I vaguely remember something like this being brought upon but couldn't find the issue.

    Thoughts?

    discussion 
    opened by FagnerMartinsBrack 25
  • Allow Objects and Arrays to be stored as JSON

    Allow Objects and Arrays to be stored as JSON

    Continued from #283

    Messed up the previous pull request, so I've made a fresh clean one. This one also removes the json configuration directive, in favour of the automatic JSON object and array parsing.

    README updated to reflect the new behaviour. Tests updated, and additional tests added to test new functionality.

    feature 2.0 
    opened by dhoulb 25
  • Should return null if  setting is JSON and cookie contains invalid JSON?

    Should return null if setting is JSON and cookie contains invalid JSON?

    In an attempt to make sure my site doesn't break nomatter how bad people try to mess with my preference cookies I found out the library breaks if the cookie contains either no or invalid JSON.

    I am now solving this with a try/catch:

    try {
        prefs = $.cookie('prefs');
    } catch (e) {
        nukeCookieAndSetDefaultSettings();
        return false;
    }
    

    Perhaps the library should return null if pasing the JSON fails?

    discussion 
    opened by danielcha 25
  • incompatability with php encoded cookies containing space in value

    incompatability with php encoded cookies containing space in value

    the problem is that php encodes space into +, and jquery cookie does not decode it accordingly

    here's test case showing the problem

    <?php
    setcookie('b', 'kala mägi+');
    ?><!doctype html>
    <head>
    <title>cookie test</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
    <script type="text/javascript" src="https://github.com/carhartl/jquery-cookie/raw/67fb34f6a866c40d0570265e8fa5911605d92616/jquery.cookie.js"></script>
    </head>
    <body>
    <script type="text/javascript">
    document.write("document.cookie: <b>" + document.cookie + '</b><br/>');
    
    document.write("cookie 'c' value: <b>" + $.cookie('c') + '</b><br/>');
    $.cookie('c', 'kala maja+');
    
    document.write("cookie 'b' value: <b>" + $.cookie('b') + '</b><br/>');
    </script>
    </body>
    </html>
    

    this results:

      document.cookie: c=kala%20maja%2B; b=kala+m%C3%A4gi%2B
      cookie 'c' value: kala maja+
      cookie 'b' value: kala+mägi+
    
    bug 
    opened by glensc 25
  • Feature: Allow the storage of objects. Degrades gracefully.

    Feature: Allow the storage of objects. Degrades gracefully.

    Added tests. MIME type fix for server. raw option as JSON value bug fix. Allow the storage of objects in cookies. Degrades gracefully. Older browser support with crockford's JSON.js (https://github.com/douglascrockford/JSON-js)

    In Dev Tools:

    $.cookie('foo')
    42
    $.cookie('foo',{bar: 42})
    "foo=%7B%22bar%22%3A42%7D"
    $.cookie('foo')
    Object
        bar: 42
        __proto__: Object
    $.cookie('bar')
    null
    
    opened by jpillora 23
  • Cookies doens't save on Safari

    Cookies doens't save on Safari

    The cookies doesn't seem to be saved if it's opened with an apple device (mac/iphone/ipad). Does anyone else noticed this? I've a site disclaimer on opening, and the cookie is attached on the 'I agree' button. It works fine with IE, Firefox, etc. But not with the iphone/ipad/mac and with safari.

    Edit: The problem seems to be with Safari. Safari doesn't save the cookie. How can we fix this?

    opened by Carlowww 22
  • Converters for writing/reading values

    Converters for writing/reading values

    Allow setting up converters, which will give developers much gained flexibility over json = true.

    // write and read converters
    $.cookie.converter = [JSON.stringify, JSON.parse];
    // single function becomes read converter
    $.cookie.converter = function (value) { return parseInt(value); };
    

    That could even make deprecation of json = true work (upon first read/write, JSON converters were set up when we find config.json to be true). We could also keep this config as a convenience shortcut for setting up the JSON converters.

    Also: such a converter function could be build in a way that they skip values with say a particular prefix. That will make developers life much easier when dealing with JSON as well as standard cookies, in that they, when implementing a converter according to their needs, won't have to toggle (and remember when to toggle) the json config.

    discussion 
    opened by carhartl 21
  • SyntaxError: JSON.parse: unterminated string

    SyntaxError: JSON.parse: unterminated string

    I apologize in advance if I'm missing something obvious, but I have some pretty simple json...

    {"links": [{"name": "AOL","url": "www.aol.com"}, {"name": "Yahoo!","url": "www.yahoo.com"}, {"name": "Microsoft","url": "www.microsoft.com"}, {"name": "CNN","url": "www.cnn.com"}, {"name": "Apple","url": "www.apple.com"}, {"name": "Digg","url": "www.digg.com"}, {"name": "Amazon","url": "www.amazon.com"}]}

    ...which I'm storing in a cookie.

    I'm using "$.cookie.json = true;" which works fine, but when I try to read it back (Firefox 18 - Mac) I get the message...

    SyntaxError: JSON.parse: unterminated string.

    I used firebug to trace it and when it gets to the line...

    value = value.slice(1, -1).replace('"', '"').replace('\', '');

    The cookie variable result is...

    "{"links\": [{\"name\": \"AOL\",\"url\": \"www.aol.com\"}, {\"name\": \"Microsoft\",\"url\": \"www.microsoft.com\"}, {\"name\": \"CNN\",\"url\": \"www.cnn.com\"}, {\"name\": \"Yahoo!\",\"url\": \"www.yahoo.com\"}, {\"name\": \"Apple\",\"url\": \"www.apple.com\"}, {\"name\": \"Digg\",\"url\": \"www.digg.com\"}, {\"name\": \"Amazon\",\"url\": \"www.amazon.com\"}]}"

    If I replace all the "\" with "" it works fine. I've double checked that my json validates, so I'm thinking it must be an issue with the escaping replace statement (only the first one seems to be escaped properly). If there's anything else I can provide, please let me know. For now, I've found that using the "raw" option sidesteps this issue. Thanks so much for all of your work on this plugin. It's a huge help.

    bug 
    opened by stazna01 20
  • $.cookie() should default path to '/'

    $.cookie() should default path to '/'

    $.cookie() should default path to '/'

    The default of using the current url as the path is super confusing. This is not mentioned in the docs, and I found it quite surprising. Cost me quite a few hours of frustration.

    opened by ssoroka 19
  • Use of [ ] in the name of a cookie

    Use of [ ] in the name of a cookie

    I work with a framework and the cookie writed on login is named :

    splash[name]

    I can read the value with the plugin

    $.cookie('splash[name]') returns 1 and it's ok but when I try to change the value like : $.cookie('splash[name]','0');

    Then it's create a cookie with the name splash%name%5D and the value 0 I had set, but It's not the same cookie...

    How can I work arround this issue ? (It seems the framework needs the [ ] )

    on jsfiddle with a document.write we see the cookie is name splash%5Bname%5D

    http://jsfiddle.net/powerMugen/acGYp/3/

    opened by PowerMugen 17
Releases(v1.4.1)
An AngularJS module that gives you access to the browsers local storage with cookie fallback

angular-local-storage An Angular module that gives you access to the browsers local storage Table of contents: Get Started Video Tutorial Development

Gregory Pike 2.9k Dec 25, 2022
京东快速提取 cookie 工具 golang版本

说明 v1.x 版本(tag) 本地运行,本地提取 京东的cookie 本地提取工具(小白专用) 双击exe文件,运行服务,后用本地的浏览器打开 http://127.0.0.1:29099 来辅助提取你的cookie v2.x 版本(tag) 服务器运行,客户端自行扫码提取,服务端自动更新cook

scjtqs 72 Aug 25, 2021
JDsms Cookie

京东短信获取Cookie PHP 环境运行(请确定运行环境). 自行修改 /api/sendNotify.php 里的 企业微信推送 参数 /images目录下 wx.png和qq.png 替换自己微信和QQ群 二维码图片 自用 仅用于测试和学习研究,禁止用于商业用途,您必须在下载后的24小时内从计

null 2 Feb 14, 2022
Vanilla JS that seamlessly add a notice for the European Cookie Law to any website

Notice: CookieNoticeJS is not under active development for the time being (and not GDPR compliant for what I know). Check AOEPeople fork instead. Cook

Alessandro Benoit 44 Aug 26, 2022
A JSON polyfill. No longer maintained.

?? Unmaintained ?? JSON 3 is **deprecated** and **no longer maintained**. Please don't use it in new projects, and migrate existing projects to use th

BestieJS Modules 1k Dec 24, 2022
⚠️ [Deprecated] No longer maintained, please use https://github.com/fengyuanchen/jquery-cropper

Cropper A simple jQuery image cropping plugin. As of v4.0.0, the core code of Cropper is replaced with Cropper.js. Demo Cropper.js - JavaScript image

Fengyuan Chen 7.8k Dec 27, 2022
CasperJS is no longer actively maintained. Navigation scripting and testing utility for PhantomJS and SlimerJS

CasperJS Important note: the master branch hosts the development version of CasperJS, which is now pretty stable and should be the right version to us

CasperJS 7.3k Dec 25, 2022
⚠️ [Deprecated] No longer maintained, please use https://github.com/fengyuanchen/jquery-viewer

Viewer A simple jQuery image viewing plugin. As of v1.0.0, the core code of Viewer is replaced with Viewer.js. Demo Viewer.js - JavaScript image viewe

Fengyuan Chen 1k Dec 19, 2022
No longer actively maintained.

Vide No longer actively maintained. I am not interested to maintain jQuery plugins anymore. If you have some fixes, feel free to make PR. Easy as hell

Ilya Caulfield 3.3k Dec 20, 2022
No longer actively maintained.

Remodal No longer actively maintained. I am not interested to maintain jQuery plugins anymore. If you have some fixes, feel free to make PR. Responsiv

Ilya Caulfield 2.8k Dec 11, 2022
Marquee is a VS Code extension designed to naturally integrate with your development flow, so that you will no longer lose track of your thoughts while you're coding

Marquee Stay organized with minimal context switching, all inside your Visual Studio Code. Marquee is a VS Code extension designed to naturally integr

stateful 60 Dec 13, 2022
"Longer in Twitter" est une extension Chrome affichant les TwitLonger directement dans un tweet.

Longer in Twitter "Longer in Twitter" est une extension Chrome affichant les TwitLonger directement dans un tweet. Installation Longer in Twitter ne f

Johan le stickman 4 Sep 22, 2022
⚠️ This project is not maintained anymore! Please go to https://github.com/visjs

vis.js (deprecated!) ❗ This project is not maintained anymore! (See Issue #4259 for details) We welcome you to use the libraries from the visjs commun

null 7.9k Dec 27, 2022
An aggregator for communities of Boilers, maintained and developed by Purdue students

Boiler Bulletin An aggregator for communities of Boilers, maintained and developed by Purdue students. Users can: Post links to online communities for

Kai Tinkess 2 Jan 23, 2022
Easy-to-use , actively maintained discord bot written in dJS V13 with customizable features

Multi-purpose discord bot Found a bug? Notes There are some modules missing, you can still start the bot but there are some things within the source t

locus 7 Nov 28, 2022
CloudSecWiki is a cloud security oriented knowledge base maintained by HuoCorp.

CloudSecWiki CloudSecWiki is a cloud security oriented knowledge base maintained by HuoCorp. CloudSecWiki web address:cloudsec.huoxian.cn Local Deploy

HuoCorp 26 Dec 4, 2022
🚌 • community maintained APIs for Poland's public transport

?? Poland's Public Transport API Simple, open and community-maintained REST API you can use in your project limitlessly. ?? Let's talk · ?? Contribute

Jan Szymański 17 Dec 24, 2022
🔍 Remake of Reguleque's front-end, a search engine for government employees. Maintained by the América Transparente foundation.

regulf-react Frontend for Reguleque, a search engine for chilean public workers records' as obtained through transparency databases. Get started To ru

América Transparente 3 Dec 15, 2022
This repository is exclusive to javascript bootcamp, organized at GDSC TIU. Maintained by Gourav Ghosal

JAVASCRIPT BOOTCAMP This repository is exclusive to javascript bootcamp, organized at GDSC TIU. An introductory resource by Gourav Ghosal, Chapter Lea

DSC TIU 15 Nov 26, 2022