Saturday, 13 May 2017

javascript cookie

<html>
<head>
  <script type="text/javascript">
function setCookie(cname, cvalue, exdays) {
    var cname = document.getElementById("cookie_name").value;
    var cvalue = document.getElementById("cookie_value").value;
    var exdays = document.getElementById("cookie_expire").value;
    exdays = parseFloat(exdays);
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getAllCookie() {
    var decodedCookie = decodeURIComponent(document.cookie);
    document.getElementById("all_cookie").innerHTML = decodedCookie;
}

function getCookie() {
    var cname = document.getElementById("cookie_name_search").value;
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            document.getElementById("cookie_by_name").innerHTML = c.substring(name.length, c.length);
            return
        }
    }
}
  </script>
</head>
<body>
    <input id="cookie_name" placeholder="cookie name" type="text" />
    <input id="cookie_value" placeholder="cookie value" type="text" />
    <input id="cookie_expire" placeholder="cookie life (days)" type="number" />
    <input onclick="setCookie()" type="button" value="create cookie" />
    <br />
    <input onclick="getAllCookie()" type="button" value="show all cookie" />
    <span id="all_cookie"></span>
    <br />
    <input id="cookie_name_search" placeholder="cookie name search" type="text" />
    <input onclick="getCookie()" type="button" value="show cookie by name" />
    <span id="cookie_by_name"></span>
</body>
</html>

reference:
https://www.w3schools.com/js/js_cookies.asp
https://www.google.ca/search?q=chrome+cookie&oq=chrome+cookie&aqs=chrome..0j69i57j0l4.7115j0j8&sourceid=chrome&ie=UTF-8



No comments:

Post a Comment