Harshitha
Harshitha

Reputation: 13

How to get the browser Cookies using JavaScript

I want to get the Browser cookies using JavaScript.I tried the below code , but i am not getting the cross domain cookies.

Here is the code:

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

Does anybody solve this.

Upvotes: 1

Views: 3488

Answers (1)

xShirase
xShirase

Reputation: 12399

In most situations, you cannot read cross domain cookies, for security reasons.

Each cookie has a domain of definition, and your browser reads those to decide which cookies you can read according to which domain you're on.

If you have control of both domains, you can modify cookie settings on domain B to allow them to be read by domain A, or code a cookie getter to get the values. Be creative!

Upvotes: 2

Related Questions