How to set custom cookies using Firefox Add-on SDK (using Services from Firefox Add-on SDK)

坚强是说给别人听的谎言 提交于 2019-12-12 02:45:55

问题


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:


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:

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");
}


来源:https://stackoverflow.com/questions/34304889/how-to-set-custom-cookies-using-firefox-add-on-sdk-using-services-from-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!