// ==UserScript== // @name 微博一键拉黑 // @name:EN Weibo Quick Block User // @name:zh-CN 微博一键拉黑 // @namespace http://tampermonkey.net/ // @version 1.0.7 // @description 一键拉黑微博用户。在博主、转发者、评论者及正文中@提及的用户名旁显示拉黑按钮。 // @description:EN One-click block Weibo users. Adds a block button next to post authors, reposters, commenters, and @mentions in post bodies. // @author Moran // @homepageURL https://github.com/morandot/userscripts // @supportURL https://github.com/morandot/userscripts/issues // @match https://weibo.com/* // @match https://www.weibo.com/* // @run-at document-idle // @noframes // @grant GM_addStyle // @license MIT // @icon https://weibo.com/favicon.ico // ==/UserScript== (function () { 'use strict'; GM_addStyle(` .weibo-block-btn { display: inline-flex; align-items: center; justify-content: center; margin-left: 6px; padding: 1px 6px; font-size: 12px; border-radius: 6px; background-color: rgba(255, 77, 79, 0.15); color: #ff4d4f; cursor: pointer; transition: all 0.2s ease; white-space: nowrap; vertical-align: middle; } .weibo-block-btn:hover { background-color: rgba(255, 77, 79, 0.25); } .weibo-block-btn.blocked { background-color: rgba(82, 196, 26, 0.15); color: #52c41a; cursor: default; } .weibo-block-btn.loading { opacity: 0.6; cursor: wait; } .weibo-block-btn:disabled { pointer-events: none; } @media (prefers-color-scheme: dark) { .weibo-block-btn { background-color: rgba(255, 99, 99, 0.2); color: #ff7875; } .weibo-block-btn:hover { background-color: rgba(255, 99, 99, 0.35); } } `); // Relative URLs keep every request same-origin on both weibo.com and // www.weibo.com (the script matches both). const BLOCK_URL = "/ajax/statuses/filterUser"; // Profile links carry the uid (/u/); @mentions inside post bodies // and comment bodies carry only the nick (/n/). Both are same-origin // weibo.com links and both get block buttons; /n/ links resolve their uid // lazily via /ajax/profile/info?screen_name=… on first click. const NAME_SELECTOR = 'a[href*="/u/"]:not([data-block-added]), a[href*="/n/"]:not([data-block-added])'; const NICK_INFO_URL = "/ajax/profile/info?scene=profile&screen_name="; // /n/ anchors resolve their uid lazily on first click; results are // cached for the lifetime of the page. const nickToUid = new Map(); // Current (2026) comment lists render each reply as .item1/.item2 > … > // div.text, where the author is a direct child of .text and the body // lives in a sibling . The legacy div[data-comment-id] markup is // gone from the feed, so comment items are treated as whitelists: only // the author link gets a block button; avatar links and @mentions inside // the comment body are skipped. const COMMENT_ITEM_SELECTOR = ".item1, .item2"; const COMMENT_AUTHOR_PARENT = "div.text"; // Older comment markup, still used on some weibo pages/modals. const LEGACY_COMMENT_BODY = 'div[data-comment-id] span[class*="cmt_text"]'; let myUid = ""; let injectScheduled = false; const pendingRoots = new Set(); function extractUid(value) { if (value == null) { return ""; } const normalized = String(value); const uidFromUrl = normalized.match(/\/u\/(\d+)/); if (uidFromUrl) { return uidFromUrl[1]; } const uidFromDigits = normalized.match(/^\d+$/); return uidFromDigits ? uidFromDigits[0] : ""; } // Get the uid a profile anchor points at, or null when the anchor is a // /n/ mention whose uid must be resolved on click. function anchorUid(a) { let parsedUrl = null; try { parsedUrl = new URL(a.href); } catch (e) { return null; } if (parsedUrl.origin !== window.location.origin) { return null; } const uidMatch = parsedUrl.pathname.match(/^\/u\/(\d+)/); if (uidMatch) { return uidMatch[1]; } const nickMatch = parsedUrl.pathname.match(/^\/n\/(.+)$/); if (nickMatch) { const nick = safeDecodeNick(nickMatch[1]); return (nick && nickToUid.get(nick)) || null; } return null; } // Malformed percent-encoding in a hand-written href must not throw // (URIError) and break the whole injection batch. function safeDecodeNick(raw) { try { return decodeURIComponent(raw); } catch (e) { return null; } } // Resolve a /n/ anchor to a uid on click (cached). Returns null when // the nick does not exist or the lookup fails. async function resolveNickUid(a) { const nickMatch = new URL(a.href).pathname.match(/^\/n\/(.+)$/); if (!nickMatch) { return null; } const nick = safeDecodeNick(nickMatch[1]); if (!nick) { return null; } if (nickToUid.has(nick)) { return nickToUid.get(nick); } const res = await fetch(NICK_INFO_URL + encodeURIComponent(nick), { credentials: "same-origin", headers: { "x-requested-with": "XMLHttpRequest" }, }); if (!res.ok) { throw new Error("Unexpected HTTP status " + res.status); } const data = await res.json(); // Missing nick: {"user":{},"message":"该昵称当前没有人使用","abnormal":true,"ok":1} const uid = data && data.ok === 1 && data.user && data.user.idstr ? String(data.user.idstr) : (data && data.ok === 1 && data.data && data.data.user && data.data.user.idstr ? String(data.data.user.idstr) : ""); if (!uid) { return null; } nickToUid.set(nick, uid); return uid; } function getMyUid() { const candidates = [ window.$CONFIG && window.$CONFIG.uid, window.$CONFIG && window.$CONFIG.user && window.$CONFIG.user.uid, window.__INITIAL_STATE__ && window.__INITIAL_STATE__.config && window.__INITIAL_STATE__.config.uid, window.__INITIAL_STATE__ && window.__INITIAL_STATE__.loginUserInfo && window.__INITIAL_STATE__.loginUserInfo.uid, document.body && document.body.dataset && document.body.dataset.uid, document.documentElement && document.documentElement.dataset && document.documentElement.dataset.uid, ]; for (const candidate of candidates) { const uid = extractUid(candidate); if (uid) { myUid = uid; return myUid; } } return myUid; } try { getMyUid(); } catch (e) { console.error("[weibo-block] Error getting myUid:", e); } function getXsrfToken() { return document.cookie.match(/XSRF-TOKEN=([^;]+)/)?.[1] || ""; } function setButtonState(btn, text, state) { btn.textContent = text; btn.classList.toggle("loading", state === "loading"); btn.classList.toggle("blocked", state === "blocked"); btn.disabled = state === "loading" || state === "blocked"; if (state === "error") { btn.style.backgroundColor = "rgba(255, 0, 0, 0.3)"; } else { btn.style.removeProperty("background-color"); } } async function blockUser(uid, btn) { setButtonState(btn, "处理中...", "loading"); try { const res = await fetch(BLOCK_URL, { method: "POST", headers: { "Content-Type": "application/json", "x-xsrf-token": getXsrfToken(), "x-requested-with": "XMLHttpRequest", }, body: JSON.stringify({ uid: uid, status: 1, interact: 1, follow: 1, }), }); if (!res.ok) { throw new Error("Unexpected HTTP status " + res.status); } const data = await res.json(); // ok === 1 is the authoritative success flag (verified against the live // API: block returns result:"true", unblock returns result:true). // Treat a missing result field as success; only an explicit false-ish // result counts as failure, so contract changes degrade gracefully. const blocked = data.ok === 1 && data.result !== false && data.result !== "false"; if (blocked) { setButtonState(btn, "已拉黑", "blocked"); } else { setButtonState(btn, "失败", "error"); } } catch (err) { console.error("[weibo-block] Request failed:", err); setButtonState(btn, "出错", "error"); } } function collectNameNodes(root) { const nodes = []; if (!root) { return nodes; } if (root === document) { return Array.from(document.querySelectorAll(NAME_SELECTOR)); } if (root.nodeType !== Node.ELEMENT_NODE) { return nodes; } if (root.matches(NAME_SELECTOR)) { nodes.push(root); } return nodes.concat(Array.from(root.querySelectorAll(NAME_SELECTOR))); } function injectButtons(root) { const nameNodes = collectNameNodes(root); // Snapshot at inject time; the click handler re-checks via getMyUid(). const currentMyUid = getMyUid(); nameNodes.forEach(a => { // Icon-only or empty anchors (avatar , inline , icon , …) // have no text to label the button with, so skip them entirely. // SVGAnchorElement lacks innerText, hence the fallback chain. const label = a.innerText || a.textContent || ""; if (label.trim() === '') { a.setAttribute("data-block-added", "true"); return; } // Only same-origin profile links may be blocked: /u/ anchors // carry the uid directly; /n/ mention anchors resolve it on // click. External sites whose path merely contains /u/ or // /n/ are rejected instead of getting a live block button. let parsedUrl = null; try { parsedUrl = new URL(a.href); } catch (e) { parsedUrl = null; } const isProfileLink = parsedUrl && parsedUrl.origin === window.location.origin && (/^\/u\/(\d+)$/.test(parsedUrl.pathname) || /^\/n\/(.+)$/.test(parsedUrl.pathname)); if (!parsedUrl || !isProfileLink) { a.setAttribute("data-block-added", "true"); return; } const uid = anchorUid(a); if (currentMyUid && uid && uid === currentMyUid) { a.setAttribute("data-block-added", "true"); return; } if (a.nextElementSibling && a.nextElementSibling.classList.contains("weibo-block-btn")) { a.setAttribute("data-block-added", "true"); return; } // Comment items: only the author link (direct child of div.text) // gets a button. Avatar links and @mentions inside the comment body // are skipped. Legacy comment markup is also excluded. const inCommentItem = a.closest(COMMENT_ITEM_SELECTOR); if (inCommentItem && !a.parentElement.matches(COMMENT_AUTHOR_PARENT)) { a.setAttribute("data-block-added", "true"); return; } if (a.closest(LEGACY_COMMENT_BODY)) { a.setAttribute("data-block-added", "true"); return; } const btn = document.createElement("button"); btn.type = "button"; btn.textContent = "拉黑"; btn.className = "weibo-block-btn"; btn.setAttribute("aria-label", "拉黑用户 " + label.trim()); btn.addEventListener("click", e => { e.preventDefault(); e.stopPropagation(); if (btn.disabled) { return; } const anchor = a; // /u/ anchors know their uid up front; /n/ anchors resolve it first. const knownUid = anchorUid(anchor); if (knownUid) { blockUser(knownUid, btn); return; } setButtonState(btn, "解析中...", "loading"); resolveNickUid(anchor) .then(resolvedUid => { if (!resolvedUid) { setButtonState(btn, "用户不存在", "error"); return; } // Re-check at click time: the closure's uid snapshot may predate // login, and the resolved nick can belong to the user themself. const nowMyUid = getMyUid(); if (nowMyUid && resolvedUid === nowMyUid) { setButtonState(btn, "自己", "blocked"); return; } return blockUser(resolvedUid, btn); }) .catch(err => { console.error("[weibo-block] Nick resolution failed:", err); setButtonState(btn, "出错", "error"); }); }); a.setAttribute("data-block-added", "true"); a.insertAdjacentElement("afterend", btn); }); } function scheduleInject(root) { pendingRoots.add(root || document); if (injectScheduled) { return; } injectScheduled = true; requestAnimationFrame(() => { const roots = Array.from(pendingRoots); pendingRoots.clear(); injectScheduled = false; roots.forEach(injectButtons); }); } function startObserver() { const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { mutation.addedNodes.forEach((node) => { if (node.nodeType === Node.ELEMENT_NODE) { scheduleInject(node); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); } if (document.body) { startObserver(); } else { window.addEventListener("DOMContentLoaded", startObserver, { once: true }); } scheduleInject(document); })();