javascript - 如何杀死僵尸 cookies

标签 javascript html cookies

我不确定我的问题是否与 this one 有关还是不是。

IE9 会在关闭浏览器后删除此 cookie(预期),但 Chrome 12、Firefox 5 和 Opera 11 不会。 (在下面的示例测试过程中,每个浏览器在单击“删除帐户”后都关闭了。然后它们在短时间后重新打开,并且在除 IE9 之外的所有浏览器中,cookie 仍然存在。)

用例: Cookie 在用户最后一次访问 1 年后过期。帐户删除应删除 cookie。

问题:
(1/2) 为什么 IE9 做了正确的(预期的)事情而其他的却没有?
(2/2) 如何确保所有浏览器都销毁此 cookie?

示例:

login.html

<!doctype html>
<html>
    <head>
        <title>Create Cookie Example</title>

        <script>
            function setCookie() {
                var expDate = new Date();
                expDate.setDate(expDate.getDate() + 365);
                document.cookie = "fakeCookie=" + escape("fake value")
                    + "; expires=" + expDate.toGMTString();
            }
        </script>
    </head>

    <body onload="setCookie()">
        <h1>Welcome</h1>
        <p>Lorem ipsum...</p>
        <hr size="1" />
        <p><a href="profile.html">User Profile</a></p>
    </body>
</html>

profile.html

<!doctype html>
<html>
    <head>
        <title>Delete Cookie Example</title>

        <script>
            function deleteConfirm() {
                if ( confirm("Are you sure you want to delete your account? "
                           + "All data will be lost; this action cannot be undone!")
                   ) deleteConfirmed()
                else return false

                return true;
            }

            function deleteConfirmed() {
                document.cookie = "fakeCookie=; expires=Thu, 01-Jan-70 00:00:01 GMT";
            }
        </script>
    </head>

    <body>
        <h1>User Profile</h1>
        <p>Lorem ipsum...</p>
        <hr size="1" />
        <p><a href="index.html" onclick="return deleteConfirm()">Delete Account</a></p>
    </body>
</html>

编辑:原始帖子错误地将 login.html 标识为 index.html(形成循环引用,当“帐户”被删除时会重新创建 cookie。)

最佳答案

OP 提出了这个答案,并最初将其编辑到问题中。这只是为了语义而将解决方案保留在答案帖子中的转贴。

        <script>
            function deleteConfirm() {
                if ( confirm("Are you sure you want to delete your account? "
                           + "All data will be lost; this action cannot be undone!")
                   ) deleteConfirmed(); // <-- ** MISSED SEMICOLON HERE **
                else return false;      // <-- ** AND HERE **

                return true;
            }

            function deleteConfirmed() {
                document.cookie = "fakeCookie=; expires=Thu, 01-Jan-70 00:00:01 GMT";
            }
        </script>

关于javascript - 如何杀死僵尸 cookies ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6539252/

相关文章:

javascript - 有没有办法在屏幕底部的页脚中打印并显示从 JSON 到达的总和对象?

javascript - 忽略错误并继续在 IE 中运行 javascript?

html - 行高没有正确继承

javascript - React - Bootstrap 下拉菜单

javascript - 使所有用户的 cookie 无效

PHP session 与 Cookie

javascript - 在 JavaScript 中,如何在不使用 JQuery 的情况下使动态创建的 tablerow 可点击?

javascript - jquery-ui可排序取消

c# - 如何在我的 ASP.net Core 应用程序中同时使用 Bearer 和 Cookie 身份验证?

javascript - ajaxStart 不适用于 onclick