Monday, 31 January 2011

Once-per-session javascript

Want to run some javascript only once per session? Here's some code, not written by me, that does the trick:

// ++++++++++++++++++++++++++++++++++++++++++ 
// Run Once Per Session 
// 
// Replace the alerts by functions that need to 
// be run once per session. 
// 
// Written by: Michael Regan 
// Website   : www.owt4nowt.ca 
// 
// Released under the GPL. 
// ++++++++++++++++++++++++++++++++++++++++++ 
var key_value = "myTestCookie=true"; 
var foundCookie = 0; 

// Get all the cookies from this site and store in an array 
var cookieArray = document.cookie.split(';'); 

    // Walk through the array 
    for(var i=0;i < cookieArray.length;i++) 
        { 
               var checkCookie = cookieArray[i]; 
        // Remove any leading spaces 
               while (checkCookie.charAt(0)==' ') 
               { 
                 checkCookie = checkCookie.substring(1,checkCookie.length); 
               } 
        
        // Look for cookie set by key_value 
                if (checkCookie.indexOf(key_value) == 0) 
               { 
                  alert("Found Cookie "); 
            // The cookie was found so set the variable 
                   foundCookie = 1; 
               } 
    } 
    // Check if a cookie has been found 
    if ( foundCookie == 0) 
    { 
        // The key_value cookie was not found so set it now 
        document.cookie = key_value; 
        alert("Setting Cookie"); 
    }  

3 comments:

  1. I just want to say thanks..

    ReplyDelete
  2. I too want to thank you for posting this. Worked like a charm!

    ReplyDelete
  3. Thank you much! This was very helpful :)

    ReplyDelete

Comments are moderated, so you'll have to wait a little bit before they appear!