1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script> 5 6 function setCookie(cname,cvalue,exdays) 7 { 8 if (!navigator.cookieEable) { 9 alert("cookie 不可用"); 10 }else { 11 //获取当前时间 12 var nowTime = new Date(); 13 //获取当前时间的毫秒数 14 var time = nowTime.getTime(); 15 //根据exdays 算不cookie过期的时间,并设置为这个时间 16 nowTime.setTime(time + exdays * 24 * 60 * 60 * 1000); 17 //设置过期日期 18 var exp = "expires" +"=" + nowTime.toGMTString(); 19 //设置cookie 20 document.cookie = cname + "=" + cvalue + ";" + exp; 21 } 22 23 } 24 25 function getCookie(cname) 26 { 27 var name = cname + "="; 28 var ca = document.cookie.split(';'); 29 30 for(var i=0; i<ca.length; i++) 31 { 32 var c = ca[i].trim(); 33 if (c.indexOf(name)==0) return c.substring(name.length,c.length); 34 } 35 return ""; 36 } 37 38 function checkCookie() 39 { 40 var user=getCookie("username"); 41 if (user!="") 42 { 43 alert("Welcome again " + user); 44 } 45 else 46 { 47 user = prompt("Please enter your name:",""); 48 if (user!="" && user!=null) 49 { 50 setCookie("username",user,30); 51 } 52 } 53 } 54 55 </script> 56 </head> 57 <body onload="checkCookie()"> 58 <button onclick="checkCookie()"> check cookie </button> 59 </body> 60 </html>