cookies - Greasemonkey 通过通配符阻止 cookie

标签 cookies greasemonkey tampermonkey

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

我找到了this答案但这只会阻止域的特定 cookie。我如何扩展它以通过通配符阻止。

最佳答案

您无法阻止 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 killer :

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+)$/, "$2");;

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

关于cookies - Greasemonkey 通过通配符阻止 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28079117/

相关文章:

未设置 JavaScript Cookie

javascript - 如何避免 javascript 从不存在的元素中检索值

javascript - 从表中获取 innerHTML

javascript - GM_registerMenuCommand()的 `accessKey`参数是什么,如何使用?

css - 无法删除某些网页上的灰度过滤器

javascript - 如何使用 Tampermonkey 删除 CSS 类?

google-chrome - 我可以使用来自实际 Chrome 安装的 cookie 运行 Selenium ChromeDriver 吗?

ruby-on-rails - 如何在功能测试中使用 Rspec 和 Capybara 测试 cookie?

javascript - Greasemonkey if/else 带有日期的超时