In JavaScript, you can use the document.cookie property to retrieve all cookies on the current page. document.cookie returns a string containing all cookies for the current page, with each cookie separated by '; '.
Here is a simple example demonstrating how to list and display all cookies on the current page:
javascriptfunction listCookies() { var cookies = document.cookie; // Retrieve all cookies for the page if (cookies) { // Split the cookie string into an array var cookieArray = cookies.split('; '); console.log('Cookies for this page:'); // Iterate through the array and print each cookie cookieArray.forEach(function(cookie, index) { console.log(index + 1 + ': ' + cookie); }); } else { console.log('No cookies found.'); } } listCookies(); // Call the function to list all cookies
In this example, we define a listCookies function that first checks if document.cookie returns any content. If cookies exist, it splits the cookie string into an array and iterates through it, printing each cookie with its index. If no cookies are found, it outputs "No cookies found."
This method is particularly useful for debugging purposes, allowing developers to quickly view all cookies on the page. If you want to further process cookies (such as deleting or modifying them), you can add the corresponding logic during iteration.