如何使用 JavaScript 在當前頁面上列出所有 cookie?


建立一個 Cookie 時,使用“path”引數。該 cookie 的路徑為設定 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

1 千+ 瀏覽次數

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.