Get browser cookies

Viewed 5092

I'm trying to get the browser cookies using: browser.cookies.getAll() but I always get this error in the console log instead:

Uncaught ReferenceError: browser is not defined

here's my code:

  var gettingAll = browser.cookies.getAll({
                     url: "url"
                    });
  console.log(gettingAll);
3 Answers

Have a look at the following...

https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

function getCookie(cname) {
  var name = cname + "=";
  var decodedCookie = decodeURIComponent(document.cookie);
  var ca = decodedCookie.split(';');
  for(var i = 0; i <ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
    }
  }
  return "";
}

Edit: fixed code block.

to get the url value u can use this solution :

    var cookiesMap = document.cookie.split(";").map( value => {
        var val =value.split("=")
        var obj = { "key" : val[0], "value" : val[1] }
        return obj;
        });

    for( var i = 0 ; i < cookiesMap.length ; i++ ){
        if( cookiesMap[i].key==="url"){
            console.log(cookiesMap[i].value);
        }
    }

hope it helps :)

browser is indeed undefined. It's not a native JavaScript object.

You should use document.cookie (see here) instead.

Related