Deleting cookies with JavaScript in Firefox extension

北城以北 提交于 2019-12-13 05:38:07

问题


I have searched a lot for deleting all or a specific cookie with JavaScript. There are lots of posts that say its not possible 100%, or you can not delete cookies with HttpOnly flag. Then the question is how the Cookies Manager+ Firefox extension can delete cookies with JavaScript? Or how the Delete All Cookies From JavaScript Chrome extension lets programmers delete cookies by sending postMessage to his extension?

I am developing a Firefox extension and need to delete some cookies from a website.

How do I delete cookies in a Firefox extension?


回答1:


As Alexander O'Mara mentioned in a comment, Chrome and Firefox JavaScript extensions run in a context that has higher privileges than JavaScript that is included on webpages. At that higher privilege level they are permitted to make changes to cookies. Your confusion probably is that you are reading webpages that discuss what is possible for JavaScript that is running from a webpage.

While I have not tested it, the following code appears to do what you want:

var {Cc, Ci} = require("chrome");

function DeleteAllCookiesForDomain( domain ) {
    var cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);
    var iter = cookieManager.enumerator;
    var cookie_count = 0;
    while (iter.hasMoreElements()) {
        var cookie = iter.getNext();
        if (cookie instanceof Ci.nsICookie) {
            if (domain.indexOf(cookie.host.toUpperCase()) != -1) {
                cookieManager.remove(cookie.host, cookie.name, cookie.path, false);
                cookie_count++;
            }
        }
    }
    return cookie_count;
};

The above code is slightly modified from code found in How do I delete cross site cookies with Firefox 22+ extension?.

However, the above code is inefficient as it iterates over all cookies, not just those from the domain you are interested in deleting. The following uses the nsICookieManager2 interface to iterate only over those cookies for the domain which you are deleting:

//For SDK
var {Cc, Ci} = require("chrome");
var cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager2);
//*/
/*//For restartless/bootstrap/overlay
Components.utils.import("resource://gre/modules/Services.jsm");
var cookieManager = Services.cookies;
//*/

function DeleteAllCookiesForDomain( domain ) {
    var iter = cookieManager.getCookiesFromHost(domain);
    var cookie_count = 0;
    while (iter.hasMoreElements()) {
        var cookie = iter.getNext();
        if (cookie instanceof Ci.nsICookie) {
            cookieManager.remove(cookie.host, cookie.name, cookie.path, false);
            cookie_count++;
        }
    }
    return cookie_count;
};


来源:https://stackoverflow.com/questions/35142884/deleting-cookies-with-javascript-in-firefox-extension

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