How can I list all cookies for the current page with Javascript?

后端 未结 8 1468
日久生厌
日久生厌 2020-12-13 01:34

Is there any way to, with help of Javascript, list all cookies associated with the current page? That is, if I don\'t know the names of the cookies but want to retrieve all

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 02:08

    Some cookies, such as referrer urls, have = in them. As a result, simply splitting on = will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).

    This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.

    // Returns an object of key value pairs for this page's cookies
    function getPageCookies(){
    
        // cookie is a string containing a semicolon-separated list, this split puts it into an array
        var cookieArr = document.cookie.split(";");
    
        // This object will hold all of the key value pairs
        var cookieObj = {};
    
        // Iterate the array of flat cookies to get their key value pair
        for(var i = 0; i < cookieArr.length; i++){
    
            // Remove the standardized whitespace
            var cookieSeg = cookieArr[i].trim();
    
            // Index of the split between key and value
            var firstEq = cookieSeg.indexOf("=");
    
            // Assignments
            var name = cookieSeg.substr(0,firstEq);
            var value = cookieSeg.substr(firstEq+1);
            cookieObj[name] = value;
       }
       return cookieObj;
    }
    

提交回复
热议问题