• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Get all cookies with Javascript

Get all cookies with Javascript

In my last jQuery post I looked at how to set, get and clear cookies with jQuery and now look at how to get a list of all the cookies that have been set. This is not jQuery specific and will work with just regular Javascript.

The jQuery Cookie plugin (http://plugins.jquery.com/project/Cookie) is useful for getting the value of a cookie when you already know the name of the cookie you want to query, but provides no way to get a list of all the cookies that are set.

The following function loads them all into an associative array with the cookie name as the index and the cookie value as the value:

function get_cookies_array() {

    var cookies = { };

    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }

    return cookies;
   
}

You could then get the cookies and write them out into the document like so:

var cookies = get_cookies_array();
for(var name in cookies) {
  document.write( name + " : " + cookies[name] + "<br />" );
}

Note that the "name_value[0] = name_value[0].replace(/^ /, ”);" line removes leading space from the cookie name which will be present for the second and subsequent cookies.

Check Out These Related posts:

  1. Setting cookies with jQuery
  2. Cookies and domains
  3. View and delete cookies for the current website in Firefox
  4. Selectively delete cookies in Firefox

Filed Under: Javascript

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap