Simple application of javascript cookie

  • 2021-01-02 21:45:21
  • OfStack

In my normal development of web pages, it may involve local storage in the browser. Currently, the mainstream storage methods in the browser include: cookie, xml, userData, H5's LocalStorage, etc. Cookie has limited storage data, but it is relatively convenient for operation when the amount of data is not large.

The following example is mainly to realize that a prompt box pops up when a web page is opened, but the prompt box is not displayed when the page is refreshed after the second time. Of course, you can flexibly set the time of cookie to control whether the prompt box is displayed.


<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title></title>
</head>
<body>

<script>

  var cookie = {
    setCookie:function(name,value,iDay){
      var cookieStr = '';
      if(iDay == undefined){
        cookieStr += name+'='+value+';';
      }else{
        var oDate = new Date();
        oDate.setDate(oDate.getDate()+iDay);
        cookieStr += name+'='+value+';express='+oDate;
      }

      document.cookie = cookieStr;
    },
    getCookie:function(name){
      var arr = document.cookie.split(';');
      for(var i=0;i<arr.length;i++){
        var arr2 = arr[i].split('=');
        if(arr2[0] == name){
          return arr2[1];
        }
      }
      return '';
    },
    removeCookie:function(name){
      this.setCookie(name,'1',-1);
    }
  }

  function ControlAlert(){
    var flag = cookie.getCookie('flag');
    if(!flag){
      alert(" I am the first 1 Secondary load of yo! ");
      cookie.setCookie('flag',true);
      //cookie.setCookie('flag',true,1);// If you have the first 3 The parameters are saved cookie The number of days if not set when the browser is closed cookie overdue 
    }
  }

  (function(){
    ControlAlert();
  }());

</script>
</body>
</html>

Above is the relevant operation of cookied, I hope to help you with your study.


Related articles: