如何使用 JavaScript 逐個列出當前頁面上的所有 Cookie?


在建立 Cookie 時,請使用“path”引數。路徑指向設定 Cookie 的目錄或網頁。如果想要從當前頁面檢索 Cookie,該引數可以留空。預設情況下,Cookie 屬於當前頁面。

示例

要逐個列出當前頁面的所有 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 and see the result:</p>
         <input type="button" value="Get Cookie" onclick="ReadCookie()"/>
      </form>
   </body>
</html>

更新時間:2020 年 6 月 16 日

1000+ 瀏覽次數

開啟您的 職業生涯

完成課程以獲得認證

開始使用
廣告
© . All rights reserved.