JavaScript清除所有localStorage和cookie

直接上源码吧

//清除localStorage
localStorage.clear();
//清除cookie,
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i];
    var eqPos = cookie.indexOf("=");
    var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
}

说明:清除localStorage简单管用,但cookie并不一定有用,因为cookie设置和清理都要具体到路径,而上面只清理了根目录和当前目录,若是存在N级目录的情况,还需要自行单独加路径。

感谢看完指鹤文章,希望指鹤的文章对您有所帮助。

闲暇时,指鹤喜欢写一些文章,部分发表在了豆瓣,若是您对此感兴趣,您可以点击下面连接支持下指鹤,指鹤在此表示感谢了

绝命笔记 一封匿名信引发的追寻 迷案追凶 量子危机

10 thoughts on “JavaScript清除所有localStorage和cookie

  1. LelandSek

    My brother suggested I might like this blog. He was entirely right. This post actually made my day. You cann’t imagine simply how much time I had spent for this information! Thanks!

    Reply
  2. LelandSek

    I do not even know how I ended up here, but I thought this post was good. I do not know who you are but definitely you are going to a famous blogger if you aren’t already 😉 Cheers!

    Reply
  3. LelandSek

    You actually make it appear really easy together with your presentation but I to find this matter to be actually one thing which I believe I’d by no means understand. It seems too complicated and extremely extensive for me. I am taking a look forward for your subsequent put up, I will attempt to get the cling of it!

    Reply
  4. my site

    978935 330601Hiya! Wonderful weblog! I happen to be a everyday visitor to your website (somewhat much more like addict ) of this web site. Just wanted to say I appreciate your blogs and am seeking forward for much more to come! 495481

    Reply

Leave a Reply

Your email address will not be published.