A cookie is a small piece of information (a string with key=value
pair) stored to the user’s computer. Each time a computer requests a page with the same browser, it will send the cookie too. It can be accessed any time the viewer returns to your site, provided the cookie hasn’t been deleted or expired.
If the viewer doesn’t accept cookies, then a cookie won’t be able to be set or used later.
Cookies have some significant limitations:
To create / set a cookie, just assign the name and value to document.cookie
property, in the following format:
You can’t have spaces, commas, or semicolons inside the cookie string, you should allways pass the value part of the string through encodeURIComponent()
to make sure you use URI-safe characters.
nume=valoare
- the name and value stored in cookie (the name should contain only letters, numbers, and _ ).var val_c ='value'; document.cookie ='some_name='+ encodeURIComponent(val_c);- The
encodeURIComponent()
method is applyed to encode the characters like ( =;.).
expires=date
- 'date' is a string with the date-time on which this cookie expires.var one_week = 7*24*60*60*1000; //an week in milisecunde var exp_dt = new Date(); exp_dt.setTime(exp_dt.getTime() + one_week); document.cookie ='food=fruits; expires='+ exp_dt.toGMTString();- The
toGMTString()
method converts the Date object to a string in GMT format.
max-age=seconds
- sets the time of existence of the cookie in seconds, after which period the cookie will expire.expires
nor max-age
specified it will expire when the browser window is closed.var one_week = 7*24*60*60; //an week in secunde document.cookie ='food=fruits; max-age='+ one_week;
path=path
- determines the pages in the site where that cookie can be used.//cookie 'food' is available on all pages in the '/blog' directory (including subdirectories) document.cookie ='food=fruits; path=/blog'; //cookie 'food' is available on all pages in the 'javascript/test' directory (including subdirectories) document.cookie ='color=blue; path=/javascript/test';- To set a cookie available in all the pages of your website, add the root path '/' (
path=/
).
domain=domain_name
- the domain or subdomain that can read that cookie.//cookie 'food' available on all pages of the site: coursesweb.net (including subdomains) document.cookie ='food=fruits; path=/; domain=coursesweb.net'; //cookie 'color' available on all pages of subdomain: 'bfie.marplo.net/' document.cookie ='color=blue; path=/; domain=bfie.marplo.net';
secure
- if set, the browser will send that cookie over HTTPS only.var one_week = 7*24*60*60; //one week in secunde document.cookie ='food=fruits; path=/; secure; max-age='+ one_week;
function setCookie(name, value, maxage, path){ var maxage =(!maxage) ? '' :'; max-age='+ maxage; var path =(!path) ? '' :'; path=' + path; document.cookie = name + '='+ encodeURIComponent(value) + maxage + path; }- This function can be used as in this code:
//define a cookie available one week on all pages var m_age = 7*24*60*60; setCookie('a_name', 'some-value', m_age, '/');
document.cookie
property from the browser.
document.cookie
returns a string with all cookies available in the page. A string like this:
<h4>Example document.cookie</h4> <p>If you click on the button, it will display the value returned by <em>document.cookie</em>.</p> <button id='btn1'>Cookie</button> <blockquote id='resp'>#resp</blockquote> <script> document.getElementById('btn1').addEventListener('click', (ev)=>{ document.getElementById('resp').innerHTML = document.cookie; }); </script>
document.cookie
.function getCookie(name){ var re =''; var str_c =' '+ document.cookie +';'; //puts the cookie string between a space and a ; var name =' '+ name +'='; //to look for what it's between name and = var start_c = str_c.indexOf(name); //where the name starts var end_c; if(start_c != -1) { //if contains the specified name start_c += name.length; //where the value starts end_c = str_c.indexOf(';', start_c); //where the value ends re = decodeURIComponent(str_c.substring(start_c, end_c)); //the value } return re; } var val_c = GetCookie('cookie_name'); document.write(val_c); //Displays the value of the cookie, or an empty string ''
//deletes the cookie from name //path is required only if it was used when the cookie was created function delCookie(name, path){ var path =(!path) ? '' :'; path=' + path; var two_d = 2*24*60*60; //two days in seconds document.cookie = name + "=bye; max-age=-" + two_d + path; }- Just call the delCookie('cookie_name') function.
<style> #add_fav, #show_fav { display:inline-block; font-size:18px; margin:5px 8px; padding:4px 5px; } #add_fav { background:#dee0fe; width:350px; } #show_fav { border:1px solid #000; background:#b0eeb0; vertical-align:top; width:250px; } #show_fav em { font-weight:700; } #set_c { display:block; margin:8px auto; } </style> <h4>Example JS script with cookie</h4> <p>Fill in the text boxes at the left and then click 'Save Favorite', it calls the 'setCookie()' function that will store them in cookies that will expire in five days.<br> Click on "Show Favorites", it calls the "getCookie()" function, this will get the data from cookies and will display the preferences you have added.<br> - If you close this window and reopen it, when you click on "Show Favorites", it will display your preferences added earlier.<br><br> Then clck "Delete cookie" button, it calls the delCookie() function that deletes these cookies.<br> The next click on "Show Favorites" will display nothing because the cookies with the preferences where deleted.</p> <div id='add_fav'> Favorite Color: <input type='text' id='color' maxlength='40' /><br> Favorite fruits: <input type='text' id='fruits' maxlength='40' /><br> Favorite quote: <input type='text' id='quote' size='35' maxlength='80' /><br> <em id='resp'></em> <button id='set_c'>Save Favorite</button> <em id='resp'></em> </div> <div id='show_fav'> <button id='get_c'>Show Favorites</button> <button id='del_c'>Delete cookie</button> <div> Favorite Color: <em id='c_color'></em><br> Favorite fruits: <em id='c_fruits'></em><br> Favorite quote: <em id='c_quote'></em> </div> </div> <script> //sets cookie name with value (available 5 days on all the pages) function setCookie(name, value, maxage, path){ var maxage = 5*24*60*60; //5 days in seconds document.cookie = name + '='+ encodeURIComponent(value)+'; max-age='+ maxage +'; path=/'; } //returns the value of the cookie from name, or empty string function getCookie(name){ var re =''; var str_c =' '+ document.cookie +';'; //puts the cookie string between a space and a ; var name =' '+ name +'='; //to look for what it's between name and = var start_c = str_c.indexOf(name); //where the name starts var end_c; if(start_c != -1) { //if contains the specified name start_c += name.length; //where the value starts end_c = str_c.indexOf(';', start_c); //where the value ends re = decodeURIComponent(str_c.substring(start_c, end_c)); //the value } return re; } //deletes the cookie from name function delCookie(name){ var two_d = 2*24*60*60*1000; //two days in seconds document.cookie = name + '=bye; path=/; max-age=-'+ two_d; } //array with names for cookie (the same with input id) var arr_co =['color', 'fruits', 'quote']; //the click on #set_c saves data in cookie document.getElementById('set_c').addEventListener('click', (ev)=>{ for(var i=0; i<arr_co.length; i++) setCookie(arr_co[i], document.getElementById(arr_co[i]).value); document.getElementById('resp').textContent ='- Data saved'; }); //the click on #get_c displays data from cookie document.getElementById('get_c').addEventListener('click', (ev)=>{ for(var i=0; i<arr_co.length; i++) document.getElementById('c_'+arr_co[i]).textContent = getCookie(arr_co[i]); }); //the click on #del_c Delete data saved in cookie document.getElementById('del_c').addEventListener('click', (ev)=>{ for(var i=0; i<arr_co.length; i++){ delCookie(arr_co[i]); document.getElementById('c_'+arr_co[i]).textContent =''; } }); </script>
<ul> <li>http://coursesweb.net/html/</li> <li>http://coursesweb.net/css/</li> </ul>
.some_class { display: list-item; }
var obj = { "courses": ["php", "javascript", "ajax"] }; var jsonstr = JSON.stringify(obj); alert(jsonstr); // {"courses":["php","javascript","ajax"]}
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>'; $dochtml = new DOMDocument(); $dochtml->loadHTML($strhtml); $elm = $dochtml->getElementById("dv1"); echo $elm->nodeValue; // CoursesWeb.net