scotthamper / cookies Goto Github PK
View Code? Open in Web Editor NEWJavaScript Client-Side Cookie Manipulation Library
License: The Unlicense
JavaScript Client-Side Cookie Manipulation Library
License: The Unlicense
See #22 for background
Errors should only be thrown when the user attempts to get a malformed cookie.
Seems like this is a great candidate to publish to npm. If there already, maybe add that to the readme?
Hello Scott,
Would you consider supporting sub-cookies like the following?
Cookies.set('key', 'subkey', 'value');
It'd be nice to have a 'raw' parameter like https://github.com/aralejs/cookie has that bypasses encoding when setting a cookie.
This cookie library (as my own cookies.js so far) appears to be failing silently when trying to set a cookie too large:
var superlongtext = "";
for (var i = 0; i < 10; i++) {
superlongtext += "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
}
Cookies.set('test', superlongtext);
var final = Cookies.get('test');
alert("Bug? " + (final !== superlongtext));
// Says "Bug? true"
JSFiddle with the error | | JSFiddle without the error (small cookie)
A possible solution would be to make this check manually when setting a cookie; set it, read it and compare it with the value that you were supposed to set. If they are different throw an error. Would love to know your thoughts on this. I am also considering allowing for an error/fallback function.
Edit: found Browser Cookie Limits, but still it's probably better to check if it was set properly.
This code is not explicitly under any license. Is there one you want to use, or would this be considered a public domain work?
Hey Scott,
Thanks for the great library! Have you thought about adding it to Bower? I think that would be helpful for a growing number of developers, myself included.
Anyway, just a suggestion. Thanks again!
Hi there,
Was working with this library on Safari and Chrome (local environment) and was unsuccessful in setting cookies when I explicitly defined "domain" and "expires" options.
It is successful in setting cookie without options. Is this a known behavior or perhaps user error?
Would like to talk more, thanks and looking forward to your reply. Best, Isa
I'm getting the following error in IE 11:
`expires` parameter cannot be converted to a valid Date instance
I've tracked the error down to the _isValidDate
method evaluating to [object Array Iterator]
instead of [object Date]
. As far as I can tell this is happening when the testKey
is removed in the _areEnabled
method.
It looks like the later versions of jsDom
aren't playing nicely with Cookies. Per your example, I've tried the following:
import {jsdom} from 'jsdom'
let Cookies
if (process.env.NODE_ENV === 'test') {
Cookies = require('cookies-js')(jsdom().defaultView)
} else {
Cookies = require('cookies-js')
}
export default Cookies
Cookies.method()
work as expected in production and development, but Cookies
is undefined
when I run my unit tests. Is there something I'm missing?
Thanks
Hi, I can't find any documentation which supports your library's notion that cookie values should be encoded. We have cookies names which contain the []
characters so we're unable to use your awesome library :(
When trying to use it with grunt-bower-install I get the following message:
cookies-js was not injected in your file.
Please go take a look in "app/bower_components/cookies-js" for the file you need, then manually include it in your file.
If added manually within bower HTML comments, it will be removed when using grunt-bower-install.
Hi Scott, awesome work here, thank you.
I was wondering about how the library compares to js-cookie
, which seems like a very similar project.
I'd be happy to have some insights as to why use one over another or what makes this library better.
Thanks for any information on this 👍
Tom
For example, the vertical bar |
is unnecessarily escaped in cookie values.
Check the RFC... only five non-control ASCII characters need to be escaped in cookie values: space, comma, semicolon, double-quote, and backslash. This question is also clearly answered on stackoverflow.
When using percent-encoding, it's also important to escape the percent symbol. Here's how to percent-encode just the characters in cookie values that need it:
value.replace(/[ %",;\\]/g, function(s) { return "%" + s.charCodeAt().toString(16) })
Application breaks when trying to read the cookies.
If one of the cookies contains a value with % the application stops!
I think maybe need to wrap the decodeURIComponenet with try and catch
Thanks for this component this is very helpful.
error code:
Uncaught URIError: URI malformed
at decodeURIComponent ()
at Function.n._getKeyValuePairFromCookieString (app.js:40)
at Function.n._getCacheFromString (app.js:40)
at Function.n._renewCache (app.js:40)
at Function.n.get (app.js:40)
at Function.n._areEnabled (app.js:40)
at i (app.js:40)
at app.js:40
at Object. (app.js:40)
at Object.r.105._process (app.js:40)
import * as cookies from 'cookies-js';
yields:
error TS7016: Could not find a declaration file for module 'cookies-js'. 'node_modules/cookies-js/dist/cookies.js' implicitly has an 'any' type.
I believe there's (at least) two ways to resolve this.
a) Include explicit "typings" into the package.json file, telling tsc where to look.
"typings": "dist/cookies.d.ts",
this is what I've done locally for now.
b) Submit type definitions to https://github.com/DefinitelyTyped/DefinitelyTyped and they will then become available under the new "@types/" package type with npm.
I think because navigator.cookieEnabled always returns true.
Reading the docs I have not found a way to set session cookies. Is this possible or not supported yet? Thanks.
Cookies.enabled returns 'false' even when cookies are enabled. I'm not sure why this is.
html file looks like....
<script type="text/javascript" src="cookies.min.js"></script>
<script type="text/javascript" src="scripts.js"></script>
js file looks like....
console.log(Cookies.enabled);
And the console log it returning false. Oh, I'm using the mini file too.
Semver is tricky: moving src/x
to dist/x
without a symlink is a breaking change.
Why? Because on a (published) package level, the "interface" is actually the files that others "require". You haven't changed your library's interface, but that's not the only interface.
So given you're in "before-1.0.0" mode, this should have been a minor bump, not a patch bump.
Just asking if this is something welcome before i open a PR. It's sometimes convenient to retrieve all the cookies in a raw. Quickly done implementation
function getAll () {
var len = Cookies._cacheKeyPrefix.length
if (Cookies._cachedDocumentCookie !== Cookies._document.cookie) {
Cookies._renewCache();
}
var cookies = {}
for (key in Cookies._cache) {
cookies[key.substr(len)] = decodeURIComponent(Cookies._cache[key])
}
return cookies
}
Mind a PR for this, or you'd prefer to keep the API ultra slick?
Is there a way to clear all cookies under a domain, for example when a user logs out?
What is type of value? You pass string
and don't say a word if it is possible to pass JS objects.
// Setting a cookie value
Cookies.set('key', 'value');
Cookies.set('key', {foo: 10, bar: "BAR"}); // <== is this possible?
Very nice library. Having split feelings about its by-default JSON encoding of the cookie value, however. This causes simple string literal cookie values to be saved with wrapped double-quotes around 'em. If you use this library for both reading and saving values - not such a big problem. The thing about cookies - they are usually accessed by a server-side technology too and that's where things get weird. You need to run an additional json-decode on the server-side to remove "extra" double quotes.
It would be nice if there were a way to disable by-default JSON encoding through options.
Not sure if this is by design, but cookies named after properties of Object.prototype
are not placed into the resulting set of cookies.
For example, this means that if one has a cookie named constructor
, this cannot be accessed by this library. Other less likely examples are to be found at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
Coming from PHP world and conceived the usefulness of PSR (PHP Standards Recommendations). I think that we should have a unified interface for a stable and lightweight component like Cookie.
Last night, it cost me a lot of time to compare the different of Cookie libraries like js-cookie vs ScottHamper/Cookies vs florian/cookie.js. I wonder why libraries' authors don't spend time together to design a unified interface for Cookie. We also don't have the feature that big company like Google used to set "multiple values to a key" (Youtube.PREF: {hl=en&abc=xyz&...}).
An interoperable unified interface helps library user much when choosing a good one and swapping to the right one in the forest of libraries of JS community.
Type: Bug
Description: Expiring a cookie sets its value as a string, "undefined"
.
What I would expect: The value would be the 'default' value for cookies, or, undefined
. This is important for libraries that check for the existence of a cookie by its value, which is important given that there is no other method to check for existence.
Cause: I suspect that this is what happens: Cookies.expire
delegates to Cookies.set
, passing undefined
as the value. That method then delegates to _generateCookieString
to compute the actual value to set. L88, within that method, is the likely culprit. undefined + ""
gets converted to "undefined"
.
If you're interested in a fix, I can whip up a PR.
Temporary Fix: Fix the value of any cookie in your code after retrieving it.
var cookie = Cookies.get('cookieName');
if (cookie === 'undefined') { cookie = undefined; }
Example coffeescript:
Cookies.set("key", value, {
# page specific
path: window.location.pathname,
# expire in 1 day
expires: 24 * 60 * 60,
})
Chrome seems ok with about script, not sure about Firefox/Safari/other browsers.
according to rfc6265 (http://tools.ietf.org/html/rfc6265#section-4.1.1),
cookie-value can be double quoted.
set-cookie-header = "Set-Cookie:" SP set-cookie-string
set-cookie-string = cookie-pair *( ";" SP cookie-av )
cookie-pair = cookie-name "=" cookie-value
cookie-name = token
cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE )
cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E
; US-ASCII characters excluding CTLs,
; whitespace DQUOTE, comma, semicolon,
; and backslash
token = <token, defined in [RFC2616], Section 2.2>
When a server send a cookie:
< Set-Cookie: foo="MTYyODNlMTc1ODIyNTA4NGMzMDg4N2RhNDg0NTZjZmQxMDJiNA==";Path=/;Expires=Mon, 19-May-2014 10:32:57 GMT
my brower (Chrome) got:
var foo = Cookies.get('foo')
// foo == '"MTYyODNlMTc1ODIyNTA4NGMzMDg4N2RhNDg0NTZjZmQxMDJiNA=="'
which is unexpected.
Hello!
Thanks for this library.
Could you please add unminified version of the library file to the dist
directory? Right now it contains only cookies.min.js
, but I would like to use cookies.js
in my project.
Of course I can include it from src
directory, but it's a bad practice that can potentially break compatibility (when you decide to split source into several files for example).
Thanks!
If I am in mydomain.com
and attempt to Cookies.set('foo', 'bar', {domain: 'ANOTHERdomain.com'})
, nothing will happen, as I understand it.
In other words, the write silently fails. Wouldn't it be good to do some sanity checks regarding secure/domain/path options for ensuring .set
always does what we believe to?
Small request: would you mind creating semver tags for new releases? For an example of what I mean, check out jQuery's tags list — front-end dependency managers like Bower use these tags instead of the package.json version number.
Hi, thank you for this great library,
Can you please fix the issue with Cookies.enabled
, it is not working neither in chrome nor IE11.
Console on Chrome and IE11 return undefined
for Cookies.enabled
It doesn't work in browser environment. Or at least explain how to deploy it in a browser env. In your docs you write:
So it is pretty natural to assume that in a browser it should be the same, since you do not provide any other info about how to run it in a browser:
const Cookies = require('cookies-js')(window);
window.Cookies = Cookies;
But the result is
Cookies === undefined.
How does it work in a browser?
If we import in TypeScript external module, src/cookies.d.ts causes the compile error TS2307.
External module style of TypeScript
/// <reference path="./node_modules/cookies-js/src/cookies.d.ts"/>
import Cookies = require('cookies-js');
var bar = Cookies.get('test');
$ tsc test.ts --module commonjs
test.ts(3,26): error TS2307: Cannot find external module 'cookies-js'.
I have two requests for this project:
a) change the Cookie.set function, so that not only a key and value as paramters are possible but also a single key-value object containing several cookie values.
i.e.
Cookie.set({
option: true,
option2: false
}, {
domain: '/'
});
b) change the Cookie.set and get function, so that JSON values are accepted and parsed accordingly.
When I tried to minify the cookies.js file. The compiler complains:
/* Minification failed. Returning unminified contents.
(3454,88-109): run-time error JS5017: Syntax error in regular expression: /[^!#-+--:<-[]-~]/g
*/
I think the correct expression should be /[^!#-+\--:<-\[\]-~]/g
The square bracket should be escaped.
i use firefox with web developer tool bar. When i disable All cookies and i call Cookies.enabled property, i have following error:
ReferenceError: Cookies is not defined
so this feature is not working for me.
thanks!!
Hi,
The library ignores the values like $ : while encodingUriComponent for the VALUE to set the cookie.
This breaks certain scenarios.
encodeUriComponent takes care of all these things and we should simply call it without the regex.
Please fix this or I can PR it.
Hello!
I would propose to add a has
method to simplify testing for cookie existence.
So we can write:
if (Cookies.has('foo')) { ... }
instead of
if ('undefined' !== typeof Cookies.get('foo')) { ... }
.
Thanks!
The current version at npm/bower points to 1.1.0 although it got the additional feature to pass the 'Infinity' expiration since last month (see 738ebf0). Their referenced version is therefore out of sync and throws an error if not passing a valid date or number. As its going to be confusing for others - I recommend to publish a minor upgrade with the latest changes.
Thank you for changing project path....
Is it make you any good other than breaking people stuff?
Once again, thank you very, very much.
It would be nice for sites that use friendly iframes to specify which document is used:
window.document.cookie
vs
window.top.document.cookie
Hi,
I have a question about sharing data between two different domains.
Does it possible through cookies ?
Can you suggest me on this.
Raja K
I meet the Cookies.expire doesn't work problem, cause by wrong way to set Cookies.default.
My stupid way is that, Cookies.default = { expires: 3600 }
.
That stupid mistake will make the Cookies.default.path change to undefined
, which will cause Cookies.set('key')
set the cookie at current path
.
Then when you use Cookies.expire('key')
will not expire the Cookie key
in the current path
. You can still get the cookie by Cookie.get('key')
.
If someone meet the problem that Cookies.expire doesn't work as you wish. Maybe you set the Cookies.default with the stupid way , just like me
So, which way is the better way to set Cookies.default.
setDefault
, Cookies.setDefault({ expires: 3600 }).just like some other Project . eg: i18next, i18next.init({yourSetting}).Hello
I have used your library for detecting cookie is disabled or not. But i am always get true
Below is the my sample code
<script src="./src/cookies.js"></script>
<script>
(function() {
var testKey = 'cookies.js';
var areEnabled = Cookies.set(testKey, 1).get(testKey) === '1';
Cookies.expire(testKey);
alert(areEnabled);
})();
Uncaught URIError: URI malformed
at decodeURIComponent ()
at rawurldecode (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/lib/php.default/php.default.min.js?ver=4.3.5:659:35)
at s.render (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/js/backend/composer-atts.js?ver=4.3.5:131:41)
at s. (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/js/backend/composer-view.js?ver=4.3.5:189:56)
at Array.forEach (native)
at Function.j.each.j.forEach (https://www.beyondroi.com/wp-admin/load-scripts.php?c=1&load%5B%5D=hoverInt…ery-ui-button,jquery-ui-dialog,editor,wplink,media-upload&ver=4.4.9:65:605)
at s.changeShortcodeParams (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/js/backend/composer-view.js?ver=4.3.5:182:19)
at s.appendShortcode (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/js/backend/composer-view.js?ver=4.3.5:424:18)
at s. (https://www.beyondroi.com/wp-content/plugins/js_composer_salient/assets/js/backend/composer-view.js?ver=4.3.5:366:22)
at Array.forEach (native)
In Google Chrome, if input data is incorrect, 'decodeURIComponent' method throws an exception with error string 'URIError: URI malformed'. This error causes cookie reading through 'Cookies' to stop working.
Actual behavior: code throws an error
Expected behavior: cookies with incorrect value not being returned. (possible solution: catch errors when '_getKeyValuePairFromCookieString' function is called or add error handling callback to Cookies API)
Environment: Chrome 33
To reproduce this error: invoke 'decodeURIComponent('%D0%EE%F1%F1%E8%FF')' in Chrome 33
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.