carhartl / jquery-cookie Goto Github PK
View Code? Open in Web Editor NEWNo longer maintained, superseded by JS Cookie:
Home Page: https://github.com/js-cookie/js-cookie
License: MIT License
No longer maintained, superseded by JS Cookie:
Home Page: https://github.com/js-cookie/js-cookie
License: MIT License
Could production-ready releases of the code be versioned, i.e. tagged? This could simplify knowing how much the code has changed and when. Right now, we version the cookie code internally--the downside being that our numbers aren't indications of your changes, just that we downloaded a new version.
Added options.port - so that can unset them;
Line 32: options.port? '; port=' + options.port : '',
Can call with
$.cookie(name,null,{domain: 'dev.example.com',path: '/',port :'8080'});
Hope that helps - really nice concise plugin.
I was working with a cookie that uses url encoding (val=a=1&b=2&c=3;), but when I queried $.cookie('val'), I would get "a" as the response. I made the following change, which fixed this problem. Thought I would pass along the change, in case it helps someone else:
if (decode(pair.shift()) === key) return decode(pair.join("=") || '');
the pair.shift & pair.join makes it return the whole string "a=1&b=2&c=3", instead of just "a".
I have used the plugin for setting a cookie and getting the same in the same session, Until the browser is closed. It is working in all major browsers except Google chrome. Kindly help me regarding this issue.
I'm using mod_rewrite for clean urls and I discovered that the path for http://domain.com/test is different from http://domain.com/test/ it might be worth adding to the documentation as its messed me around a bit.
My solution was to manually specify the path..
var p = document.location.pathname;
p = ( p.indexOf('/',1) == -1 ? p : path.substring(0, p.lastIndexOf('/')+1) );
$('test','var',{path:p});
If you have a coookie array, the Regex eval dont work.
Try finding: cookie[1000]
The result is null.
Any solution ?
loading:
causes $.cookie
to dissapear. maybe jQuery core allows to prevent this?
<!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>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
</head>
<body>
<script type="text/javascript">
document.write($.cookie)
</script>
</body>
</html>
results:
undefined
Setting a cookie with a string variable fails because the ignores "objects".
So:
var myVar = 'bar';
$cookie('foo', myVar);
needs to be:
var myVar = 'bar';
$cookie('foo', String(myVar));
Not sure if this was by design?
All the tests die with a message like:
Died on test #1: QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead - {}
... does not seem to work. I'm trying to create a cookie using
$.cookie(cookieName, cookieValue, {expires: new Date(Date.now() + (30 * 60 * 1000)), domain: vDomain, path: vPath});
But every Browser stores this cookie as session cookie. Can anyone reproduce this?
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+
I set a cookie if it does not exist and set the value to 0. However, as soon as I close the browser the cookie gets deleted.
var loginCount = parseInt($.cookie("loginCount"));
if(!loginCount){
$.cookie("loginCount", 0, { expires: 7 });
loginCount = 0;
alert("Cookie created");
}
$("#numberOfLogins").text(loginCount);
// cookie is incremented upon login
cookie 1.0 mostly works but has subtle issues that you've since fixed. i think others would benefit from direct access to the improved plugin.
Hi carhartl,
Thanks for the great plugin. it works in chrome, firefox and opera, but not on ie,7,8,9 and safari. you could check it live on sampath.ind.in. I want to keep image slider in same position even after postback. Could yu please help me to fix this?
Many thanks in advance
I test online, using a subdomain (like test.something.com) and in FF it works fine but in Chrome it takes my first write attempt but "rewrite" not so fine anymore, funny thing it let me rewrite it once as I saved modifications to js file and then again not.
If possible I would like to apply cookie for all subdomains of domain, I hear there should be a dot before domain name to do this, but with or without domain option, it does not work. It allows only to change the cookie value once after I resave the .js file
my code snippet (simplified, using jQ and jQ-UI .dialog() ):
. . . .
buttons: {
"set to PN": function() {
$.cookie('region', 'PN', { expires: 90 }); //,path: '/', domain: '.example.com' (dotBeforeDomain = RFC2109)
location.reload(true);
$( this ).dialog( "close" );
},
"set to TN": function() {
$.cookie('region', 'TN', { expires: 90 });
location.reload(true);
$( this ).dialog( "close" );
}
}
});
. . . . .
Getting this error with jquery 1.7.1
...remove inline documentation
Hi there, is it possible to set hours or minutes in the expire values at all? not sure what's possible here?
Hi, I'm trying to delete cookies using that plugin, but it don't work for my by the next way using the 'path' and 'expires' option:
$.cookie('p', 'value', { expires: 1, path: '/'});
alert(document.cookie);
$.cookie('p', null, { expires: -1, path: '/' });
alert(document.cookie);
but, if put the next, it works fine:
$.cookie('p', 'value', { expires: 1, path: '/'});
alert(document.cookie);
$.cookie('p', null, { expires: 1, path: '/' });
alert(document.cookie);
so, if i want to delete a cookie using your plugin I need to put the same options that I used for its creation, really?
Another thing for the plugin-users that are using firefox, deleted cookies appears in the Control Panel --> Cookies but I think it's a bug because with document.cookie the erased cookie doesn't appears, and using Opera works fine.
cheers.
I can't believe I don't see more of this on your issues, but since PHP allows us to store cookies as pseudo arrays, it would be nice if either:
a) jquery.cookie.js allowed this interpretation of bracketed cookie names
b) At minimum, cookie should honor the "raw" setting for the names of cookies, not just their content. That was at least we could simulate the PHP architecture.
Hello,
when I set up fookie ie for subdomain.site.com - it creates cookie for: ".subdomain.site.com"
How I can create cookie for: "subdomain.site.com" ? Without leading dot...
I tried doing alert(options.domain), right before:
return (document.cookie = [
encodeURIComponent(key), '=', options.raw ? value : encodeURIComponent(value),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
it alerts the correct subdomain (without a leading dot (.) ) - so not sure why this is happening..
The code I use to set the cookie:
$.cookie('from', 'test', { expires: 7, path: '/', domain: "subdomain.site.com" });
THank you!
Hello
Thanks for your excellent plug-in.
I'm just a beginner so apologies in advance if this is a waste of your time. Would be very grateful for your help.
I have used j-query-cookie on my site home page to manage the display of a message in a modal window.
I have set the cookie to expire after 365 days - seems to work on FF, Opera and Chrome - (in that it doesn't appear if I close and reopen the browser) but not IE9. (The modal window appears every time I close and reopen the browser.)
I have as follows
jQuery(function ($) {
if ($.cookie('modal') != 'shown')
{
//$.cookie('modal', 'shown');
// SET THE COOKIE FOR 365 DAYS
$.cookie('modal', 'shown', { expires: 365 });
// code to show modal
// Load dialog on page load
$('#basic-modal-content').modal();
// Load dialog on click
//$('#basic-modal .basic').click(function (e) {
//$('#basic-modal-content').modal();
//return false;
///});
// end cookie if
}
});
eg,we have a cookie("test", "github"),when use $.cookie("test"), i get the result of "github",i think it would return github.
then, pass the value of cookie to the server witted by java, get the value is ""github"" when debuging.
Shouldn't the tests pass?
OSX Chrome
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2
Tests completed in 46 milliseconds.
5 tests of 12 passed, 7 failed.
Since I found no documentation here I felt like sharing the following from theelectrictoolbox.com:
http://www.electrictoolbox.com/jquery-cookies/
It covers most of the plugin and should get you started.
From the Chrome console:
$.cookie('test', 'a=b', {raw: true})
"test=a=b"
$.cookie('test', {raw: true})
"a"
Encoding the value is an easy work around, but that's not always possible. For example, Google Analytics uses raw cookie values with lots of embedded = characters, and this bug prevents getting those values correctly.
This issue is for IE 8 only. I haven't tried it in IE9 nor IE7.
$.cookie("a", "123", {path: window.location.pathname}); returns the string:
"a=123; path=yourpagepath"
But running
Works fine in Chrome an FF7
Hi!
I found that when you update an existing cookie you have to specify your options again to not get the default ones. Example:
$.cookie('my_cookie', 'foo', { expires: 30, path: '/' });
$.cookie('my_cookie', 'bar');
That would result in a cookie with default options. Caused my quite an headache for a while :) It would be nice if this wasn't needed, if at all possible.
Hi, when i invoke
$.cookie('new_cookie', null, {path: ''});
cookie is not removed.
I think when value === null expiration should then be set for "Thu, 01-Jan-1970 00:00:01 GMT"
and would be working.
Hi,
Thanks so much for the cookie plugin! It's awesome. :)
Would you consider adding a version number to the code? I know your code does not change often, but I would love to keep track by checking the version number.
OT:
Is this the new home for the cookie plugin? I googled and the old site/docs did not show up like they normally do.
Just wondering if Github will be the new home for downloading your cookie plugin?
Thanks!
m
$.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.
I don't have a test case written up for you, but I can at least describe the issue. :)
In IE8, when you set a cookie to an empty value, it encodes it in a rather odd fashion.
Code on our index (simplified to the point):
function hasCookie(name) { return (jQuery.cookie(name) != null) }
function runblah() {
if(hasCookie('referrer')) { return true; }
jQuery.cookie('referrer', document.referrer, {
path: '/',
domain: 'blah.com',
expires: 1
});
window.location = "/blah.cgi?returnTo=/";
}
What happens on IE8:
You visit index, with no referrer. (document.referrer is '', NOT NULL, per IE8's JS Console)
runblah() runs, sets referrer cookie to '', then sends us to blah.cgi.
blah.cgi does some back-end accounting stuff, then sends us back to index.
Index loads and runs again. On FF and Chrome, jQuery.cookie('referrer') returns '' as it should. On IE8, however, it returns null. In our case, this caused a nasty redirection loop.
When we inspected document.cookie, we found that it was being set to the following: "x=y; y=z; referrer" (x and y are placeholders for other cookies that showed up in there)
When you pass a null value to the cookie the expires value of options is modified and options should be readonly (at least I assume that). We had problems with such a case because we used a global object for options. It only happened on IE browsers.
Maybe the solution is to clone the options object into a local variable.
Hello
the mod security of my hoster revealed this :
[Mon Apr 18 15:46:28 2011] [error] [client 93.10.132.37] ModSecurity: Access denied with code 406 (phase 2). Pattern match "(?:\b(??:type\b\W_?\b(?:text\b\W_?\b(?:j(?:ava)?|ecma|vb)|application\b\W*?\bx-(?:java|vb))script|c(?:opyparentfolder|reatetextrange)|get(?:special|parent)folder|iframe\b.{0,100}?\bsrc)\b|on(??:mo(?:use(?:o(?:ver|ut)|down|move|up)|ve)|key(?:press|d ..." at REQUEST_FILENAME. [file "/usr/local/apache/conf/modsec2.user.conf"] [line "116"] [id "950004"] [msg "Cross-site Scripting (XSS) Attack"] [data ".cookie"] [severity "CRITICAL"] [tag "WEB_ATTACK/XSS"] [hostname "www.planete-flop.fr"] [uri "/blog/wp-content/plugins/font-resizer/js/jquery.cookie.js"] [unique_id "TaxAtMcQgBQAABEmCI4AAABp"]
The script match this pattern
((?:opyparentfolder|reatetextrange)|get(?:special|parent)folder|iframe\b.{0,100}?\bsrc)\b|on(??:mo(?:use(?:o(?:ver|ut)|down|move|up)|ve)|key(?:press|d ...")
Is there an option for to make the cookie work on different pages/directories on my site? It seems like it kind of works with just default but not all the time. Any ideas?
code:
$.cookie('unlockGate', 'true', { expires: 180, domain: '.'+window.location.hostname, path:'/' });
in FF8, param "expires" set as session, not 180 days.
in Google Chrome, param "expires" set 180 days.
So, I have duplicate code here.... just attached to two different selectors (based on where you are located on site).
This code will not work for the $.cookie('name', null) to delete cookie.
$('a.campus-select').click(function(){
var $campus = $(this).attr('rel');
// set or delete cookie
if ($campus == "all") {
$.cookie('Campus', null); // TRYING TO DELETE COOKIE - BUT WONT HERE. WILL BELOW?
console.log("current campus is " + $campus);
console.log($.cookie('Campus'));
} else {
$.cookie('Campus', null);
// setCookie('Campus',$campus,365);
$.cookie('Campus', $campus, { expires: 365, path: '/' });
console.log("just set the cookie for /");
}
});
This code will work work for the $.cookie('name', null) to delete cookie.
$('a.home-campus-select').click(function(){
var $campus = $(this).attr('rel');
var $update_links = $('ul.filter li a');
// set or delete cookie
if ($campus == "all") {
$.cookie('Campus', null); // BUT DELETING A COOKIE HERE WORKS... ?
console.log("current campus is " + $campus);
console.log($.cookie('Campus'));
} else {
$.cookie('Campus', null);
// setCookie('Campus',$campus,365);
$.cookie('Campus', $campus, { expires: 365, path: '/' });
console.log("just set the cookie for /");
}
});
I have literally copied and pasted the code into each other - they are nearly identical - yet - the top will not delete the cookie with $.cookie('Campus', null);
I may be completely missing this - and if so, that is fine :) I just want to know what I'm doing wrong - or if there is a bug!
If you want to see it in action: 2011.newlifechurch.tv
Working one is on the ** home page ** - bottom updates, you can see in the console. When clicking 'All' in the filter - you will see null show up (make sure you select a campus first!)
Then on the updates page (2011.newlifechurch.tv/updates) - if you do the same with the filters, you will see that it won't say 'null', instead saying a campus name.
error: SCRIPT438: Object doesn't support property or method 'cookie'
Hi !
I know this is a FAQ, and it's explained in the documentation that if you want a cookie to be valid on the whole site, it needs to be created with something like
$.cookies("foo", "bar", {
path : "/"
});
I'm in a situation where the cookie is created in a login page, where the user is redirected when they try to access a page like "/foo/bar/baz". But I want the cookie to be valid on all pages, so I obviously create it with the "path" : "/" options.
For some reason, when I open the Webdevelopper "View cookie information pane" in FF8, or when I use the settings screen to look at cookie details in Chrome, the cookie is displayed with a path like "foo/bar" (typically, the parent of the page I tried to access). So obvioulsy if I navigate to another page, the browser does not send the cookie.
I debugged the source of the plugin, and as far as I can tell the call
"""javascript
document.cookie = name + '=' + encodeURIComponent(value) + expires + path + domain + secure;
"""
is done with path being "; /", which is what I expect, isn't it ?
I have absolutely no clue as to what can be messing up with the cookies on the client side ; is there any thing I can have a look at ? Could the server somehow modifiy the cookie, so that on a subsequent request the browser feel the need to modify its 'path' ?
Any help welcome.
Perhaps this is intended, but the detection below "key and at least value given, set cookie" fails to accept numbers, as
Object.prototype.toString.call(value)
returns
[object Number]
not
[object String]
Perhaps the incoming value could be cast to a string if non-empty, or [object Number] also allowed?
Thanks for putting this plugin together.
How can I set an expiration in minutes instead of days?
Thanks,
Jacob
I have a valid cookie with a value of '' (empty string). In Chrome and FF, i get the '' back properly. In IE, i get null back from the cookie plugin. The cookie does exist, but the format in IE is different from Chrome and FF. The following are what i'm seeing (with a cookie name of ptvid)
In Chrome, the cookie shows the following in the debugger: "ptvid="
In FF, the cookie shows the following in the debugger: "ptvid="
In IE, the cookie shows the following in the debugger: "ptvid"
Since IE is missing the trailing equal sign, the cookie plugin can't find it and therefore it falls through the for look without finding a match. The cookie compare using substring needs to take care of this situation with IE and return empty string if the cookie name is found without the trailing equal sign.
hello,
So far didn't had any problems with server (installing different frameworks etc).
Now I needed the cookies plugin - and could not make it to set the cookie, I downloaded the tests to the server, and I got 4 errors:
Maybe someone could help me?
Thank you very much
I don't understand the check for String(value) !== '[object Object]', what if that was the value of your cookie?
How to check if the plugin is loaded, before using it?
$.fn.cookie doesn't work properly, because telling me it's undefined but it isn't.
as the title... does the plugins works with IE7?
Is encodeURIComponent() correct here for escaping the value of the cookie? Shouldn't it be "escape"?
Cookies come in and out of your plugin just fine, but cookies containing a pathname are not really usable as-is by anyone else because of your choice of encoding.
A call to $.cookie() without any attributes should give an object with the names and values of each cookie.
We could use something like this (or hopefully something better):
var cdata = {};
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';'), i;
for (i = 0; i < cookies.length; i+=1) {
var cookie = jQuery.trim(cookies[i]);
var eqi = cookie.indexOf("=");
if (eqi <= -1) {
continue;
}
cdata[cookie.substring(0, eqi)] = decodeURIComponent(cookie.substring(eqi+1, cookie.length));
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.