如何在 JavaScript 中使用 document 物件訪問 Cookie?


使用 JavaScript,您可以輕鬆地使用“document.cookie”屬性訪問/讀取 Cookie。由於 document.cookie 物件的值就是 Cookie 本身,因此讀取 Cookie 與寫入 Cookie 一樣簡單。

document.cookie 字串將保留一個用分號分隔的名稱=值對列表,其中名稱是 Cookie 的名稱,值是其字串值。

在本文中,我們將學習如何在 JavaScript 中使用 document 物件訪問 Cookie。

語法

document.cookie

返回值 - 所有 Cookie 都以單個字串的形式儲存在瀏覽器中。

document.cookie 字串將保留一個用分號分隔的名稱=值對列表,其中名稱是 Cookie 的名稱,值是其字串值。

步驟

要使用其名稱提取特定 Cookie,我們使用以下步驟。

  • 使用 document.cookie 屬性獲取所有 Cookie 字串。

  • 使用 String.split( ) 方法在每個分號(“;”)處分割字串,並將返回的陣列儲存在一個變數中。

  • 建立一個空的 Map( ) 來儲存鍵值對。

  • 遍歷陣列,並在每次迭代中以“=”分割該元素,並將它的第 0 個索引設定為 Map 的鍵,第一個索引設定為 Map 的值,使用 Map.set ( key, value ) 方法。

  • 現在您在 Map( ) 中擁有每個 Cookie 的名稱=值格式。

  • 從 Map( ) 中按名稱檢索所需的 Cookie。

示例

您可以嘗試執行以下程式碼以瞭解如何在 JavaScript 中使用 document 物件訪問 Cookie

<html>
   <head>
      <script>
         function ReadCookie() {
            var allcookies = document.cookie;
            document.write ("All Cookies : " + allcookies );
            
            // Get all the cookies pairs in an array
            cookiearray = allcookies.split(';');
            
            // Now take key value pair out of this array
            for(var i=0; i<cookiearray.length; i++) {
               name = cookiearray[i].split('=')[0];
               value = cookiearray[i].split('=')[1];
               document.write ("Key is : " + name + " and Value is : " + value);
            }
         }
      </script>
   </head>
      <body>
         <form name="myform" action="">
            <p> Click the following button to access the cookie:</p>
            <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
         </form>
      </body>
</html>

示例

在此示例中,我們首先使用 document.cookie 方法設定一些 Cookie,然後我們使用上面描述的方法按名稱檢索 Cookie。

<!DOCTYPE html>
<html>
   <head>
      <title> How to access cookies using document object in JavaScript </title>
   </head>
   <body>
      <h2> Accessing cookies using document object in JavaScript </h2>
   </body>
   <script>

      // Set some cookie to the browser
      document.cookie = "firstname=Saurabh"
      document.cookie = "lastname=Jaiswal"
      document.cookie = "age=20"

      // Print the cookie string
      document.write( document.cookie + "  ")

      // firstname=Saurabh; lastname=Jaiswal; age=20
      // There can be another cookie also printed
      // if they are saved previously in your browser

      // Get the cookie and store in a variable
      let myCookies = document.cookie
      myCookies = "firstname=Saurabh;lastname=Jaiswal;age=20"

      // Split the cookie string at every semicolon
      myCookies = myCookies.split(";")

      // ['firstname=Saurabh', ' lastname=Jaiswal', ' age=20']
      // Create a map to store the cookies in key value Pair
      let cookies = new Map();

      // Loop through the myCookies array
      for( let cookie of myCookies ){

         // Split the elements at "="
         cookie = cookie.split( "=" )

         // Set the first element as key and second element as value
         cookies.set( cookie[0], cookie[1] )
      }
      // Retrive the cookies by its name
      document.write( cookies.get( "firstname" ) + "  ");
      document.write( cookies.get( "lastname" ) + "  );
      document.write( cookies.get( "age" ) + "  ");
   </script>
</html>

總之,JavaScript 允許您使用 document.cookie 屬性訪問和讀取 Cookie。此屬性返回一個包含儲存在瀏覽器中的所有 Cookie 的字串,每個 Cookie 都表示為一個用分號分隔的名稱=值對。

要使用其名稱提取特定 Cookie,您可以將 Cookie 字串在每個分號處分割,建立一個 Map 物件來儲存鍵值對,並遍歷 Cookie 對陣列,將第一個元素設定為鍵,第二個元素設定為 Map 中的值。然後,您可以從 Map 中按名稱檢索所需的 Cookie。此技術可用於在使用者的瀏覽器中儲存和檢索資訊,例如使用者偏好或登入憑據。

更新於: 2023年1月6日

7K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告
© . All rights reserved.