René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Setting and reading cookies with JavaScript

<html>
<head>

<script>

  var cookie_name_1 = 'some_cookie_name_1';
  var cookie_name_2 = 'some_cookie_name_2';

  function set_cookie(cookie_name, cookie_value) {
//  var path     = document.URLUnencoded.replace(/http:\/\/[^/]*/,"");
    var path     = document.URL         .replace(/http:\/\/[^/]*/,"");

    // Internet Explorer bug? IE doesn't seem to accept a document name
    // as part of the file name:
    path = path.replace(/[^/]*$/,"");

    var exp_date = new Date();
    var exp_days = 100;

    path = "; path=" + path;// + ";";

    exp_date.setTime(exp_date.getTime() + (exp_days*24*60*60*1000));

    var exp      = "; expires=" + exp_date.toGMTString();
//  alert            (cookie_name + '=' + cookie_value + exp + path);
    document.cookie = cookie_name + '=' + cookie_value + exp + path ;
  }

  function get_cookie(cookie_name) {
    var all_cookie_values = document.cookie.split(';');

    for (var ix=0; ix<all_cookie_values.length; ix++) {

      // Replace possible white space at the left:
      var cookie = all_cookie_values[ix].replace(/^ */,"");

      if (cookie.indexOf(cookie_name + '=') == 0) {
        return cookie.substring(cookie_name.length+1);
      }
    }

    return 'Cookie not set.';
  }

  function fill_form() {
    document.frm.c1.value = get_cookie(cookie_name_1);
    document.frm.c2.value = get_cookie(cookie_name_2);
  }

  function set_cookies() {
    set_cookie(cookie_name_1, document.frm.c1.value);
    set_cookie(cookie_name_2, document.frm.c2.value);
  }

</script>

</head>
<body onLoad='fill_form();'>

<form name='frm'>
     Cookie 1: <input name='c1' type='text'>
  <p>Cookie 2: <input name='c2' type='text'>

  <p><input type='button' value='Set cookies' onClick='set_cookies()'>


</form>


</body>
</html>