Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify or add cookies from JavaScript? [closed]

Exactly what are the restrictions for handling browser cookies from javascript? Can I check if cookies are enabled for example?

like image 572
user207414 Avatar asked Nov 10 '09 00:11

user207414


People also ask

Can we manipulate cookies using JavaScript?

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.

How do you update existing cookies?

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.

Can you modify cookies?

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.

What happens when cookie expires JavaScript?

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.


2 Answers

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.

like image 76
jessegavin Avatar answered Sep 29 '22 11:09

jessegavin


You write a cookie and try to read back: this way, you'll know if cookies are enabled.

like image 29
jldupont Avatar answered Sep 29 '22 13:09

jldupont