今天要挑戰的是用Javascript刪除ASP.NET寫入的Cookie。

Client-Side本來就可以由document.cookie取得Cookie,其為一字串,格式類似cookie1=value1;cookie2=value2;cookie3=value3,要用得自行拆解,但不乏現成的共用函數可以代勞。若網頁有引用jQuery,jQuery Cookie Plugin是不錯的選擇。

要用jQuery Cookie Plugin刪除Cookie可以寫成$.cookie("CookieName", null);,但如果要刪除ASP.NET寫入的Cookie,必須要提供與Server端寫入時完全一致的Path、Domain、Expires才能成功。因此後方的範例程式中,刪除未設有效期限的Cookie,至少要傳入Path="/",例如: $.cookie("MyCookie", null, { path:"/" });,由於ASP.NET未指定Domain,Client-Side可以傳domain:""或逕行省略。

如果當初寫入Cookie時有設定Expires就比較麻煩些,因為Cookie的細節資訊(如有效期限)只保存在Browser裡,並不會隨Request送回Server,因此Server端連用Request.Cookies["CookieName"].Expires讀不到當初指定的有效期限(讀到的永遠都是0001/01/01 00:00:00),更甭提Javascript了。除非Javascript端能掌握正確的Expires(透過Hidden傳回前端,或採用事先約定的邏輯,不然就得筊杯了),否則就無法將Cookie刪除。在以下的範例中,驗證了只要Expires指定正確,有設期限的Cookie還是可以被刪除的(例如: AbsExprCookie)。

<%@ Page Language="C#" %>
<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            //不設期限
            Response.Cookies.Add(new HttpCookie("MyCookie", "Darkthread"));
            //設相對期限
            HttpCookie c = new HttpCookie("RelExprCookie", "Darkthread");
            c.Expires = DateTime.Now.AddMinutes(10d);
            Response.Cookies.Add(c);
            //設絕對期限
            c = new HttpCookie("AbsExprCookie", "Darkthread");
            c.Expires = DateTime.ParseExact("2009/02/28", "yyyy/MM/dd", null);
            Response.Cookies.Add(c);
        }
    }
 
    protected void btnCheckCookie_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder(
            "Cookies Count=" + Request.Cookies.Count.ToString() + "<br />");
        foreach (string ck in Request.Cookies.Keys)
        {
            HttpCookie c = Request.Cookies[ck];
            sb.AppendFormat(
                "<li>[{0}]={1}<br />Path={2}, Domain={3}, Expires={4}",
                c.Name, c.Value, c.Path, c.Domain, c.Expires);
        }
        lblDisp.Text = sb.ToString();
    }
</script>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Cookie Test</title>
    <script type="text/javascript" src="../js/jquery-1.3.1.js"></script>
    <script type="text/javascript" src="../js/jquery.cookie.js"></script>
    <script type="text/javascript">
        $(function() {
            if (document.cookie && document.cookie != '') {
                $("#dvDisp").html(
                    "<li>" + document.cookie.replace(/;/g, "<li>")
                );
            }
            $("#btnDelCookie").click(function() {
                $.cookie("MyCookie", null, { path:"/" });
                $.cookie("AbsExprCookie", null,
                    { path:"/", expires: new Date(2009, 2, 28) });
                alert("Cookies deleted!");
            });
        });
    </script>
    <style type="text/css">
    body, html { font-size: 9pt; padding: 5px; }
    fieldset { height:150px; width: 300px; 
               text-align: left; padding: 10px;}
    .fldDiv { background-color: #dddddd; margin-top: 20px; 
              width:330px; height: 180px; text-align:center;}
    #btnDelCookie { color: Blue; text-decoration: underline;
                    cursor: pointer; }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnCheckCookie" runat="server" Text="Check Cookie" 
            onclick="btnCheckCookie_Click" />
        <div class="fldDiv">
        <fieldset>
        <legend>Server View</legend>
        <asp:Label ID="lblDisp" runat="server" Text="N/A"></asp:Label>
        </fieldset>
        </div>
        <div class="fldDiv">
        <fieldset><legend>Client View</legend>
        <div id="dvDisp"></div>
        </fieldset>
        </div>
        <span id="btnDelCookie">Delete Cookie</span>
    </div>
    </form>
</body>
</html>

網頁跑起來如下圖,Delete Cookie按鈕可以刪除MyCookie及AbsExprCookie,RelExprCookie的有效期限對Javascript來說是個謎,無從刪起。刪除後按下Check Cookie,Server端會發現那個兩Cookie不見了,表示刪除成功。


Comments

Be the first to post a comment

Post a comment


45 + 22 =