如何在 JavaScript 中獲取與文件關聯的 Cookie?


在本文中,我們將學習如何在 JavaScript 中獲取與文件關聯的 Cookie。

Document 介面中提供的 cookies 屬性用於在 JavaScript 中返回與 Document 關聯的 Cookie。Cookie 是儲存在瀏覽器中以 **名稱=值** 對形式存在的小型資料字串。每個 Cookie 都用 **';'** 分隔。

Cookie 用於客戶端-伺服器應用程式。Cookie 有一個過期日期。它們的大小限制為 4KB。

為了更好地理解這個概念,讓我們在本文中進一步研究示例。

語法

獲取文件中關聯的 Cookie 的語法如下所示。

document.cookie;

示例 1

以下是一個示例程式,我們在其中顯示了文件中存在的 Cookie。

<html>
<body>
   <p id="cookie"></p>
   <script>
      document.getElementById("cookie").innerHTML = "Cookies associated with this document: " + document.cookie;
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 2

下面的程式是顯示文件中存在的 Cookie 的示例。

<!DOCTYPE html>
<html>
<head>
   <title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
   <body style="text-align : center">
      <h3>To display the domain of the server that loaded a document in JavaScript</h3>
      <p id='cookies'></p>
      <script>
         document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
      </script>
   </body>
</html>

執行上述程式碼後,將生成以下輸出。

示例 3

下面是一個示例程式,用於建立使用者定義的 Cookie。即設定和獲取 Cookie,最後顯示 Cookie。

<!DOCTYPE html>
<html>
<head>
   <title>To display the domain of the server that loaded a document in JavaScript</title>
</head>
<body style="text-align : center">
   <h3>To display the domain of the server that loaded a document in JavaScript</h3>
   <p id='cookies'></p>
   <script>
      document.cookie = "username= John Nicholas; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/"; // Set the cookie
      let x = document.cookie; // Get the cookie
      document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Delete the cookie by not specifying any value and set the expires value to past date.
      document.getElementById('cookies').innerHTML = 'The cookies associated in this document are : '+document.cookie ;
   </script>
</body>
</html>

執行上述程式碼後,將生成以下輸出。

更新於: 2022-12-08

599 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告