Search code examples
javascriptcookiesfirefox-addonfirefox-addon-sdk

Read cookies of specified host using Firefox Add-on SDK


I am developing a Mozilla Firefox extension using the Add-on SDK. On every tab change event, I want to read cookies of specified host which is open in another tab. I reached up to tab change, but am trying to figure out the way to get the cookies of specified host in recent activated tab.

var tabs = require("sdk/tabs");
tabs.on('activate', function(tab) {
    // want to get cookies here. 
});

Solution

  • Well, from within a tabs.on('activate') event handler, you have the tab. The tab object has a property url from which you can obtain the host. Once you have the host, you can get the cookies for that host. You have not stated what you want to do with them. So, here is just a way to enumerate them.

    In order to use some methods of Services.cookies (nsICookieManager2) you will also need to require Chrome Authority.

    var domainToUse = 'google.com';
    var { Services }  = require("resource://gre/modules/Services.jsm");
    var { Cc, Cu, Ci} = require("chrome");
    let cookieEnumerator = Services.cookies.getCookiesFromHost(domainToUse);
    while (cookieEnumerator.hasMoreElements()) {
      let cookie = cookieEnumerator.getNext().QueryInterface(Ci.nsICookie2); 
      console.log(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n");
    }
    

    Update for newer versions of Firefox:
    Note: At least by Firefox 50.0a2 (currently Firefox Developer Edition), it is necessary to use a slightly different call to getCookiesFromHost() to obtain the cookieEnumerator. Without the change, the call to getCookiesFromHost() will display a warning message in the Browser Console directing you to visit the nsICookieManager2 MDN documentation page which has no updated information on the warning, or any documentation on the change. I had to look in the source code to determine what was required. What appears to be desired is to pass in the current content document. However, from a background script that did not appear reasonable. The other way it is used is to just pass in an empty Object, {}. Thus, that line is changed to:

    let cookieEnumerator = Services.cookies.getCookiesFromHost(domainToUse,{});
    

    It is supposed to be for passing in "the originAttributes of cookies that would be be retrieved."

    The above code is slightly modified from my answer to "How to set custom cookies using Firefox Add-on SDK (using Services from Firefox Add-on SDK)".