Home > Blockchain >  Add a value to a cookie with expiration data?
Add a value to a cookie with expiration data?

Time:10-20

How can I add a cookie which expires in 2 months to '[email protected]' from the following code

<div id="home">
    <div class="name" my-data="123">Email: [email protected]</div> 
</div>

I think the code for the actual time should be as follows but I do not know how to add the value to it:

function myemail () {
    var expiryDate = new Date();
  expiryDate.setMonth(expiryDate.getMonth()   2);
    document.cookie = cookieName   '=y; expires='   expiryDate.toGMTString

CodePudding user response:

Assuming you have privileges to add an ID to your div, the following code works fine

<body>

    <div id="home">
        <div class="name" my-data="123" id="email-div">Email: [email protected]</div>
        <button onclick="myemail()">Set it</button>
    </div>

    <script>
        function myemail() {
            var expiryDate = new Date();
            var email = document.getElementById("email-div").textContent.split("Email:")[1]
            expiryDate.setMonth(expiryDate.getMonth()   2);
            document.cookie = 'emailCookie='   email   ';expires='   expiryDate.toGMTString()   ';path=/';
        }
    </script>

</body

Well I have used a button to trigger the action. You can do the same in any event.

CodePudding user response:

toGMTString is a function, you need to call. Replace expiryDate.toGMTString to expiryDate.toGMTString()

const Cookie = {
get: function (name) {
    const nameEq = name   "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i  ) {
        let 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;
},

set: function (name, value, hours) {
    const expires = "";
    if (hours) {
        let date = new Date();
        date.setTime(date.getTime()   (hours * 60 * 60 * 1000));
        const expires = "; expires="   date.toGMTString();
    }

    document.cookie = name   "="   value   expires   "; path=/";
}
};

You can change hours to whatever and of course this one date.setTime(date.getTime() (hours * 60 * 60 * 1000)); to the corresponding formula

Usage`

Set: Cookie.set('myemail', '[email protected]', 1460) // 1460 is 2 months in hours

Get: Cookie.get('myemail')

const email = document.getElementsByClassName('name')[0].textContent.split(' ')[1]; Cookie.set('myemail', email, 1460);

  • Related