How to set custom cookies using Firefox Add-on SDK

2019-09-13 02:44发布

I am working on creating a Firefox Add-on SDK extension that would set custom cookies (two cookies with name and value attributes) on Firefox v41, with jpm.

Essentially, if I open the add-on's Panel() and click on set, the cookie values should be set. On refresh, I should be able to see them on my developer console, in which ever tab I open. And, on reset, they should be removed.

I tried modifying the code snippet from the Add-ons Code snippets -> Cookies on Mozilla's developer website:

Services.cookies.add("http://www.google.com/", "/", "test", "value");

The issue I am facing is with the Services module. When I run my extension in debug mode, it throws ReferenceError saying that Services is not defined.

I am unable to find another way of setting the cookies permanently. Using document.cookie would set the cookie values for the panel only and that is not what I am looking for.

I also tried the Chrome way of doing it when I read somewhere that Firefox's Add-on framework is compatible with the Cookie API of Google Chrome.

Please let me know if you need more information on the issue I am facing.

1条回答
SAY GOODBYE
2楼-- · 2019-09-13 03:11

Within the Firefox Add-on SDK, you can gain access to Services using the following:

var { Services }  = require("resource://gre/modules/Services.jsm");

However, your use of Services.cookies.add() is erroneous in that you are not passing enough arguments to the method. Here is something that works:

var { Services }  = require("resource://gre/modules/Services.jsm");
let is_secure = false;
let is_http_only = false;
let is_session = false;
let expiry_date = Math.floor(Date.now()/1000 + 3600*24); //Time in seconds 1 day from now.
Services.cookies.add(".host.example.com", "/cookie-path", "cookie_name", "cookie_value",
                     is_secure, is_http_only, is_session, expiry_date);

This will result in a cookie that looks like:

Example cookie panel

In order to use some methods of Services.cookies (nsICookieManager2) you will also need to require Chrome Authority. For instance, to enumerate through the cookies you could do:

var { Cc, Cu, Ci} = require("chrome");
let cookieEnumerator = Services.cookies.getCookiesFromHost("google.com");
while (cookieEnumerator.hasMoreElements()) {
  let cookie = cookieEnumerator.getNext().QueryInterface(Ci.nsICookie2); 
  console.log(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n");
}
查看更多
登录 后发表回答