Cookie小案例 - 使用Cookie进行判断登录权限Demo

使用Cookie进行判断登录权限的小Demo

1.document.cookie 属性来创建 、读取、及删除 cookie

2.document.referrer 属性返回载入当前文档的来源文档的URL,如果是直接访问,则为null

3.重点在于登录后cookie的存储,读取cookie的值进行判断,退出后清除cookie函数

 

Demo浏览,F12打开Application,浏览Storage下的Cookies

创建A,B,C三个页面,A为登录页,B页面为过滤页,进行判断是否登录再执行跳转,用于权限阻止,C页面为最终显示页面

 

1.A页面为主页

 1 <!--登录模拟-->
 2     <input type="text" id="txt" />
 3     <input type="button" id="btn" value="点击" />
 4     <br /><br />
 5     <!--链接模拟-->
 6     <div id="cc" href="C.html">前往C页面</div>
 7     <br />
 8     <!--清除cookie-->
 9     <div onclick="clearAllCookie();" title="可用于退出登录">清除页面cookies </div>
10     <script>
11         //点击跳转过滤页
12         document.getElementById("btn").onclick = function () {
13             let usname = document.getElementById("txt").value;
14             document.cookie = "name=" + usname;
15             document.cookie = "url=" + document.getElementById("cc").getAttribute("href");
16             //查看cookie中的值
17             alert(document.cookie);
18             //过滤页
19             window.location.href = "B.html";
20         }
21 
22         //单独点击页面跳转,B页面未检测到值则回退本页面
23         //防止用户直接点击,需(登录后)才可浏览
24         document.getElementById("cc").onclick = function () {
25             window.location.href = "B.html";
26         }
27 
28         //清除所有cookie函数
29         function clearAllCookie() {
30             var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
31             if (keys) {
32                 for (var i = keys.length; i--;)
33                     document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
34             } 
35         }
36     </script>

2.B页面为过滤页,进行判断是否登录再执行跳转,用于权限阻止,本页全为js

 1     <script>
 2         //判断cookie是否为空,是则返回上一页
 3         if (getCookie("name") == "" || document.cookie.length == 0) {
 4             //判断是否是直接输入本过滤页,是则返回主页
 5             if (window.location.href == document.referrer) {
 6                 window.location.href = "../";
 7             } else
 8                 window.location.href = document.referrer;
 9         } else {
10             //获取A页面传的url
11             window.location.href = getCookie("url");
12         }
13 
14         //cookie获取值封装
15         function getCookie(sName) {
16             var aCookie = document.cookie.split("; ");
17             for (var i = 0; i < aCookie.length; i++) {
18                 var aCrumb = aCookie[i].split("=");
19                 if (sName == aCrumb[0])
20                     return unescape(aCrumb[1]);
21             }
22             return null;
23         }
24     </script>

3.C页面为最终显示页面

1    正确访问!
2     <script>
3         if (window.location.href == document.referrer) {
4             window.location.href = "../";
5         }
6     </script>

 

原文链接:【Cookie小案例 - 使用Cookie进行判断登录权限Demo】    Amaya丶夜雨博客

posted @ 2019-08-22 17:00  Amayaliu  阅读(763)  评论(0编辑  收藏  举报