Greasemonkey 通过通配符阻止 cookie

Greasemonkey block cookies by wildcard

我有一个名为 Cookie## 的 cookie,其中 ## 是一个随机数。有什么方法可以使用 Greasemonkey 来阻止任何以 "Cookie" 开头的 cookie 被阻止?

我找到了 this 答案,但这只会阻止域的特定 cookie。我如何将其扩展为也被通配符阻止。

只需找出所有以"Cookie"开头的cookie,然后一一做同样的回答。

document.cookie.split('; ')
    .map(function (x) { return x.split('=', 1)[0]; })
    .filter(function (x) { return x.substring(0, 6) === 'Cookie'; })
    .forEach(function (name){
        // set the domain
        var domain = ".jsfiddle.net";

        // get a date in the past
        var expireDate = new Date(-1).toUTCString();

        // clear the cookie and force it to expire
        document.cookie = name + "=; domain=" + domain + "; path=/; expires=" + expireDate;

    });

您无法阻止 cookie,但您通常可以在设置它们后将其删除(¡but not always! ).

获取 "Cookie###" 个 cookie 的列表并使用正则表达式遍历它们:

var mtch;
var targCookRgx = /[; ]*(Cookie\d+)=/gi;
//-- Doc.cookie value will be changing in while()
var oldCookie   = document.cookie;

while ( (mtch = targCookRgx.exec (oldCookie) ) != null) {
    eraseCookie (mtch[1]);
}

其中 eraseCookie() 是当前可用于用户脚本的最强大的 cookie 杀手:

function eraseCookie (cookieName) {
    //--- ONE-TIME INITS:
    //--- Set possible domains. Omits some rare edge cases.?.
    var domain      = document.domain;
    var domain2     = document.domain.replace (/^www\./, "");
    var domain3     = document.domain.replace (/^(\w+\.)+?(\w+\.\w+)$/, "");;

    //--- Get possible paths for the current page:
    var pathNodes   = location.pathname.split ("/").map ( function (pathWord) {
        return '/' + pathWord;
    } );
    var cookPaths   = [""].concat (pathNodes.map ( function (pathNode) {
        if (this.pathStr) {
            this.pathStr += pathNode;
        }
        else {
            this.pathStr = "; path=";
            return (this.pathStr + pathNode);
        }
        return (this.pathStr);
    } ) );

    ( eraseCookie = function (cookieName) {
        console.log ("cookieName to delete: ", cookieName);

        //--- For each path, attempt to delete the cookie.
        cookPaths.forEach ( function (pathStr) {
            //--- To delete a cookie, set its expiration date to a past value.
            var diagStr     = cookieName + "=" + pathStr + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
            //console.log ("--> Cookie str: ", diagStr);
            document.cookie = diagStr;

            document.cookie = cookieName + "=" + pathStr + "; domain=" + domain  + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
            document.cookie = cookieName + "=" + pathStr + "; domain=" + domain2 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
            document.cookie = cookieName + "=" + pathStr + "; domain=" + domain3 + "; expires=Thu, 01-Jan-1970 00:00:01 GMT;";
        } );
    } ) (cookieName);
}