gregSTam gregSTam - 4 months ago 11
Javascript Question

Count HTTP only cookies with Mozilla add-on

I'm trying develop a Firefox add-on. I would like to count the cookies that are marked as HTTP only. When manually checking, I have seen that many websites have more than one HTTP only cookie. But, my result is always

0
or
1
. Where is my fault?

Here is my code:

var {Cc, Ci, Cu} = require("chrome");
Cu.import("resource://gre/modules/Services.jsm");
var cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager2);
var tabs = require("sdk/tabs");

tabs.on('load', function(tab) {
var URL = tab.url;
var url = require("sdk/url").URL(URL);
var host = url.host;

function getCookies(host){
var cookies = cookieManager.getCookiesFromHost(host);
var count = 0;
while (cookies.hasMoreElements()){
var cookie = cookies.getNext().QueryInterface(Ci.nsICookie2);
//var count = 0;
var httpCookie = cookie.isHttpOnly;
if(httpCookie){
return count=count+1 ;
}else{
return 0;
}
console.log("Cookie host: " + cookie.host + "; Cookie Name :" + cookie.name
+ " = Cookie value:" + cookie.value + "\n");
dump("\tCookie host: " + cookie.host + " Is Domain cookie: " +cookie.isDomain
+ "; Cookie Name :" + cookie.name +" = Cookie value:" + cookie.value
+ "; Is Session Cookie :" + cookie.isSession
+ "; Expiry time :" + cookie.expiry
+ "; It is an Http only cookie :" + cookie.isHttpOnly + "\n");
}
return count;
}
var getResult = getCookies(host);
console.log("Http Cookies: " + getResult);
});

Answer

Within your function getCookies(host) you have a while loop that is intended to loop through all cookies for the specified host. However, the inner portion of that loop is only executed once.

Within that loop you have an if statement:

var httpCookie = cookie.isHttpOnly;
if(httpCookie){
    return count=count+1 ;
}else{
    return 0;
}

This statement results in the function immediately returning either a 1 or a 0 depending on if the first cookie found has the property cookie.isHttpOnly as true or false. [Note: cookie is always 0 when this if statement is executed for the first and only time.] No other cookies are checked other than the first one because you immediately return the value. Execution of your function ends at either of the two return statements within this if statement. The lines within the function after the if will not be executed.

From what you describe you desire, your if statement would be better as:

if(cookie.isHttpOnly){
    count++;
}

Note: Given that you only use cookie.isHttpOnly once, there is no need to assign it to a separate variable.

Comments