如何在JavaScript中使用文件物件訪問Cookie?
使用JavaScript,您可以輕鬆地使用“document.cookie”屬性訪問/讀取Cookie。由於document.cookie物件的value就是Cookie,因此讀取Cookie與寫入Cookie一樣簡單。
document.cookie字串將保留一個名稱=值對的列表,這些對用分號分隔,其中名稱是Cookie的名稱,值是其字串值。
在本文中,我們將學習如何在JavaScript中使用文件物件訪問Cookie。
語法
document.cookie
返回值 − 所有Cookie都以單個字串的形式儲存在瀏覽器中。
document.cookie字串將保留一個名稱=值對的列表,這些對用分號分隔,其中名稱是Cookie的名稱,值是其字串值。
步驟
要使用其名稱提取特定Cookie,我們使用以下步驟。
使用document.cookie屬性獲取所有Cookie字串。
使用String.split()方法在每個分號(“;”)處分割字串,並將返回的陣列儲存在一個變數中。
建立一個空的Map()來儲存鍵值對。
迴圈遍歷陣列,在每次迭代中以“=”分割該元素,並使用Map.set(key, value)方法將其第0個索引設定為Map的鍵,第一個索引設定為Map的值。
現在您在Map()中擁有每個Cookie及其名稱=值格式。
從Map()中按名稱檢索所需的Cookie。
示例
您可以嘗試執行以下程式碼,學習如何在JavaScript中使用文件物件訪問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。此技術可用於在使用者的瀏覽器中儲存和檢索資訊,例如使用者偏好或登入憑據。