v2ex 快速屏蔽用户

在用户评论区域添加一个 block 按钮,不用点进用户主页,点击即可 block 用户。

目前為 2022-12-21 提交的版本,檢視 最新版本

// ==UserScript==
// @name         v2ex 快速屏蔽用户
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  在用户评论区域添加一个 block 按钮,不用点进用户主页,点击即可 block 用户。
// @author       3989364
// @match        https://www.v2ex.com/t/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=v2ex.com
// @grant        none
// @license       MIT
// ==/UserScript==

class User {
  constructor() {}

  async fetchUserPage(username) {
    const resp = await fetch(`https://www.v2ex.com/member/${username}`);
    return await resp.text();
  }

  parseBlockURL(page) {
    const html = document.createElement("html");
    html.innerHTML = page;
    const fn = html.querySelector('input[value="Block"]').onclick;

    if (fn) {
      // /block/xxxx?once=19604
      return fn.toString().match("location.href = '(.+)'")[1];
    }

    return null;
  }

  async blockUser(username) {
    const page = await this.fetchUserPage(username);
    const url = await this.parseBlockURL(page);

    if (url) {
      // just dont redirect
      try {
        await fetch(url, {
          redirect: "error",
        });
      } catch {}
    }
  }

  hideUserAllReply(username) {
    if (!username) {
      return;
    }

    document.querySelectorAll("#Main .cell").forEach((cell) => {
      const u = cell.querySelector("strong> a")?.textContent;
      if (u === username) {
        cell.remove();
      }
    });
  }
}

(function () {
  "use strict";
  function addChildInThankArea(node, thankArea) {
    thankArea.appendChild(node, thankArea);
  }

  function createBlockButton() {
    const blockButton = document.createElement("a");
    blockButton.textContent = "block";
    blockButton.className = "thank";
    blockButton.style.marginLeft = "0.5rem";
    blockButton.href = "#;";

    return blockButton;
  }

  const user = new User();

  document.querySelectorAll(".thank_area").forEach((thankArea) => {
    const blockButton = createBlockButton();

    addChildInThankArea(blockButton, thankArea);

    blockButton.addEventListener("click", async function (event) {
      event.preventDefault();
      const wrapper = thankArea.parentNode.parentNode;
      const username = wrapper.querySelector("strong > a").textContent;

      if (username && confirm(`确认要屏蔽 ${username} ?`)) {
        await user.blockUser(username);
        user.hideUserAllReply(username);
      }
    });
  });
})();