Exactly what are the restrictions for handling browser cookies from javascript? Can I check if cookies are enabled for example?
JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
To update a cookie, simply overwrite its value in the cookie object. You do this by setting a new cookie on the document with the same Name, but a different Value.
Cookies are stored on the user's machine. They can be modified in any way. In fact, the cookies can just be created on the fly and sent via several utilities for making HTTP requests. It isn't even a browser problem.
If a cookie has expired, the browser does not send that particular cookie to the server with the page request; instead, the expired cookie is deleted.
Yes! Read this excellent article about using cookies with JavaScript
Here's an excerpted code example.
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
And as for testing whether they are enabled. I like jldupont's answer.
You write a cookie and try to read back: this way, you'll know if cookies are enabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With