Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách xóa tất cả cookie bằng JavaScript

Để xóa tất cả cookie, đặt ngày hết hạn (expires) về một thời điểm trong quá khứ.

Ví dụ

<html>
  <head>
    <script>
      function WriteCookie() {
        var now = new Date();
        now.setMonth(now.getMonth() - 1); // 1 tháng trước
        cookievalue = escape(document.myform.customer.value) + ";";
        document.cookie = "name=" + cookievalue;
        document.cookie = "expires=" + now.toUTCString() + ";";
        document.write("Setting Cookies: " + "name=" + cookievalue);
      }
    </script>
  </head>
  <body>
    <form name="myform" action="">
      Enter name: <input type="text" name="customer"/>
      <input type="button" value="Set Cookie" onclick="WriteCookie()"/>
    </form>
  </body>
</html>

Xóa tất cả cookie thực tế:

document.cookie.split(";").forEach(c => {
  document.cookie = c.trim().split("=")[0] + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/";
});