Results 1 to 6 of 6

Thread: javascript cookies question

  1. #1

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2000
    Posts
    537

    javascript cookies question

    I'm building an application that i need people to logon in order for them to view specific pages.

    not a problem with that.

    but what if they bookmark those pages?

    how do i create a cookie in javascript that expires when they end the session or close the browser?

    I doesn't need to be complex.

    thanks for any tips or suggestions!
    pnj

  2. #2
    Frenzied Member Rick Bull's Avatar
    Join Date
    Apr 2002
    Location
    England
    Posts
    1,444
    This is what I use, I think if you don't pass a date it expires at the end of the session:

    Code:
    //Sets a cookie. Send the name of the varible, the value, days until it expires - leave blank for no-expiration
    function setCookie(cookieName, cookieValue, cookieExpiry) {
      //If the date is not already in date format (i.e. days till expiry), and not missing
      if (!(cookieExpiry instanceof Date) && cookieExpiry != null) {
        //Convert the expiry date to the correct format
        var expiryDate = new Date ();
        expiryDate.setTime(expiryDate.getTime() + (cookieExpiry * 24 * 3600 * 1000));
        cookieExpiry = expiryDate;
      }
      //Write the cookie, and the expiration date (if present)
      document.cookie = cookieName + '=' + escape(cookieValue) + ((cookieExpiry == null) ? '' : '; expires=' + cookieExpiry.toGMTString());
      return true;
    }
    If you want the rest of the JS file (reading/deleting cookies etc) just let me know.

  3. #3

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2000
    Posts
    537
    thanks!

    yea, if you have the rest of the code that reads it that would be cool

    what i'm going to do is, if the user trys to bookmark a page, i'll read the cookie. if it doesn't exist, send them back to the login page.

    make sense?

    thanks again!
    pnj

  4. #4
    Frenzied Member Rick Bull's Avatar
    Join Date
    Apr 2002
    Location
    England
    Posts
    1,444
    Good idea. Here's the file, I think it all works fine. I added a function called sixMonths that returns the date plus six months, so that you can set cookies for that length of time.
    Attached Files Attached Files

  5. #5

    Thread Starter
    Fanatic Member
    Join Date
    Jun 2000
    Posts
    537
    great!

    thanks again!
    pnj

  6. #6

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width