sessionStorage可以作为会话计数器,localStorage可以作为Web应用访问计数器。声明一个localStorage计数变量,当刷新页面时,会看到计数器数值在增长,即使关闭浏览器窗口,然后重新访问页面,计数器会继续计数。而sessionStorage计数变量只能够在当前会话期间显示页面访问量,即使刷新页面会看到计数器在增长,而当关闭浏览器窗口,然后再试一次,计数器已经重置了。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> if(localStorage.pagecount){ localStorage.pagecount = Number(localStorage.pagecount)+1; }else{ localStorage.pagecount = 1; } document.write("总访问数:<br/>"+localStorage.pagecount); if(sessionStorage.pagecount){ sessionStorage.pagecount = Number(sessionStorage.pagecount)+1; }else{ sessionStorage.pagecount = 1; } document.write("<br/>当前会话内访问数:<br/>"+sessionStorage.pagecount); </script> </body> </html>