Skip to content

Instantly share code, notes, and snippets.

@mishalrai
Forked from atk/LICENSE.txt
Created May 14, 2018 04:40
Show Gist options
  • Save mishalrai/605e5b4110f5caed7e0ffe68b234ff2e to your computer and use it in GitHub Desktop.
Save mishalrai/605e5b4110f5caed7e0ffe68b234ff2e to your computer and use it in GitHub Desktop.
Cookie helper

Cookie helper

A small function to get the escaped value of a named cookie. There's also a bigger function that works as a cookie setting preparer, though it does only get the escaped value and does not yet fit into 140 bytes at the moment (2 bytes golfing, anyone?):

var C=function(c,d,e){e='';for(d in c)c.hasOwnProperty(d)&&(e+=(e?'; ':e)+d+'='+c[d]);return''+c!==c?e:(document.cookie.match(c+'=(.+?);')||0)[1]}
// setting a Cookie:
document.cookie = C({cookiename: 'testcookie', expires: (new Date(new Date()*1+6E10)).toGMTString()});
C('cookiename') // -> returns the still escaped value of the Cookie "cookiename"
function(
c // cookie name
){
// unescape cookie value
return unescape(
// coerces to RegExp /name=([^;]+)/ within match
(document.cookie.match(c+'=(.+?);')||0)[1]||''
)
}
// other version:
function(
c, // cookie name or cookie object
d, // placeholder
e // result for object parameterisation
){
// init result
e='';
// try to parameterize input
for (d in c)
// only unprototypical stuff is added to result in the format key=value[; ]
c.hasOwnProperty(d) && (e+=(e?'; ':e)+d+'='+c[d]);
// input is not a string?
return ''+c !== c ?
// return parameterized input
e :
// or coerce the cookiename to a regexp to match its unescaped value
(document.cookie.match(c+'=(.+?);')||0)[1]
}
function(c){return unescape((document.cookie.match(c+'=(.+?);')||0)[1]||'')}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "cookie",
"description": "Gets a cookie value by name (setting in an extra ungolfed version)",
"keywords": [
"cookie",
"value",
"by",
"name"
]
}
<!DOCTYPE html>
<title>Cookie</title>
<div>Expected value: <b>http[s]://github.com/[your username]</b> (on github content of your github tracker cookie)</div>
<div>Actual value: <b id="ret"></b></div>
<script>
// write a small example that shows off the API for your example
// and tests it in one fell swoop.
var myFunction = function(c){return unescape((document.cookie.match(c+'=(.+?);')||0)[1]||'')}
document.getElementById( "ret" ).innerHTML = myFunction('tracker')
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment