Ashish Patel Ashish Patel - 1 year ago 111
Javascript Question

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.

Answer Source

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 = '';
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.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 fail with an error message in the console directing you to visit a non-existent MDN documentation page. 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,{});

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)".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download