Block_Zhihu_Users

Block users on a website by clicking a button

当前为 2023-07-25 提交的版本,查看 最新版本

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         Block_Zhihu_Users
// @namespace    your-namespace
// @version      1.0
// @description  Block users on a website by clicking a button
// @match        https://www.zhihu.com/question/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    let executedUrls = [];

    async function blockUsers() {
        // 模拟鼠标滚轮向下滚动
        window.scrollTo(0, document.body.scrollHeight);
        await sleep(600); // 等待加载完成

        let arr = document.querySelectorAll("div.ContentItem-meta > div.AuthorInfo.AnswerItem-authorInfo.AnswerItem-authorInfo--related > div.AuthorInfo > span > div > a");

        console.log(`加载完成...arr:${arr.length}`)

        let count = 0;
        let index = 0;
        for (let a of arr) {
            index += 1;
            let userUrl = a.href;
            let urlToken = '';
            try {
                urlToken = userUrl.substring(userUrl.lastIndexOf('/') + 1);
            } catch (e) {
                console.log(`err:url:${userUrl}`);
                continue;
            }

            if (executedUrls.includes(urlToken)) {
                //console.log(`${index}/${arr.length}:Skipping ${userUrl} as it has already been blocked`);
                console.log(`${index}/${arr.length}`);
                try {
                    let b = a.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
                    b.style = 'display:none';
                } catch (e) {}
                continue;
            }

            // 检查是否已执行过该 urlToken
            if (localStorage.getItem(urlToken)) {
                //console.log(`${index}/${arr.length}:Skipping ${userUrl} as it has already been blocked`);
                console.log(`${index}/${arr.length}`);
                try {
                    let b = a.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
                    b.style = 'display:none';
                } catch (e) {}
                continue;
            }

            console.log(`${index}:${count}/${arr.length},屏蔽用户:${userUrl}`);
            const response = await fetch(`/api/v4/members/${urlToken}/actions/block`, {
                method: 'POST',
                headers: new Headers({
                    'x-xsrftoken': document.cookie.match(/(?<=_xsrf=)[\w-]+(?=;)/)[0],
                }),
            });
            try {
                let b = a.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement;
                b.style = 'display:none';
            } catch (e) {}
            count += 1;
            executedUrls.push(urlToken);
            localStorage.setItem(urlToken, 'blocked'); // 将已执行过的 urlToken 存入 localStorage
            await sleep(300);
        }

        //debugger
        if (arr.length === 0 || executedUrls.length === 0 || executedUrls.length === arr.length) {
            console.log('No more data or all urlTokens have been blocked. Simulating page scroll to load more data...');
            alert(`Block ${count} users,total:${executedUrls.length}! \n No more data or all urlTokens have been blocked. Click button or page scroll to load more data...`);
        }

        // 移动鼠标到最下面
        window.scrollTo(0, document.body.scrollHeight);
        window.focus(); // 聚焦到当前页面
        for (let i = 0; i < 5; i++) {
            const event = new KeyboardEvent('keydown', {
                key: 'G',
                code: 'KeyG',
                shiftKey: true
            });
            document.dispatchEvent(event);
            await sleep(1100);

        }
    }

    // 创建悬浮按钮元素
    const button = document.createElement('button');
    button.textContent = '屏蔽用户';
    button.style.position = 'fixed';
    button.style.bottom = '20px';
    button.style.right = '20px';
    button.style.zIndex = '9999';
    button.style.padding = '10px 20px';
    button.style.border = 'none';
    button.style.borderRadius = '10px';
    button.style.color = '#fff';
    button.style.fontSize = '16px';
    button.style.fontWeight = 'bold';
    button.style.background = 'red';
    button.style.cursor = 'pointer';

    // 添加点击事件监听器
    button.addEventListener('click', async() => {
        await blockUsers();
    });

    // 将按钮添加到页面中
    document.body.appendChild(button);

})();