How to save pre-scan settings using cookie

Scenario:

There are occasions that customers visit the same website and scan images using the same pre-scan settings like they always do. And they may want the website to memorize their previous scan settings. It can be done with a little help from a cookie.

Solution:

Please be noted, in order to demonstrate the functions step by step, we add three buttons to separate the process, which can actually be done automatically in the background with your own code logic.

In the following paragraphs, three major functions will be introduced as below. We will take "IfShowUI" property as an example:

 •Save Settings: Save customized scan settings in cookie.

 •Load Settings: Load previous saved settings from cookie.

 •Clear Settings: Clear saved cookie.

>> Save Settings:
Please remember to set period of validity to the cookie you are saving.

    // set period of validity for the cookie
    var date=new Date(); 
    var expiresDays=30; 
    date.setTime(date.getTime()+expiresDays*24*3600*1000); 
    // save the current value of IfShowUI to cookie
    document.cookie="IfShowUI=" + document.getElementById("ShowUI").checked + ";expires="+date.toGMTString();

>> Load Settings:

    // load info from cookie as string value
    var strCookie=document.cookie; 
    // check if a pre-scan settings has been saved before
    if(strCookie=="")
        alert("Please save scanning settings first.")
    else{
        // spilt the cookie string into several name/value pair
        var arrCookie=strCookie.split("; ");
        var IfShowUI;
        // iterate through the array
        // locate the cookie named "IfShowUI", and get the value
        for(var i=0;i< arrCookie.length; i++){
            var arr=arrCookie[i].split("=");
            if("IfShowUI"==arr[0]){
            IfShowUI=arr[1];
            break;
            }
        }
        // use the cookie info to set current value of "IfShowUI"
        document.getElementById("ShowUI").checked = (IfShowUI == "true");
    }

>> Clear Settings:
Please remember to set period of validity to the cookie you are saving.

    // get current time.
    var date=new Date(); 
    // set date to a time in the past
    date.setTime(date.getTime()-10000); 
    // delete the cookie
    document.cookie="IfShowUI"+"=v; expires="+date.toGMTString();

For more details, please download the Sample Code from here.

Is this page helpful?

Leave a Reply

Your email address will not be published.