anakin765 / weibo-cleaner

// ==UserScript==
// @name         weibo-cleaner
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  移除微博页面中的垃圾骚扰内容,例如:投票、推荐、荐读、"你常看的优质博主"
// @author       Roo
// @license      MIT
// @license-url  https://opensource.org/licenses/MIT
// @match        https://weibo.com/*
// @match        https://*.weibo.com/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  // 防抖函数
  function debounce(func, wait) {
    let timeout;
    return function () {
      const context = this,
        args = arguments;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        func.apply(context, args);
      }, wait);
    };
  }

  // Filter out spam items (votes, recommendations, "recommended bloggers")
  function filterSpamItems() {
    try {
      const items = document.querySelectorAll(".vue-recycle-scroller__item-view");
      if (!items.length) return;

      let stats = { votes: 0, recommends: 0, bloggers: 0 };

      items.forEach((item) => {
        const voteElement = item.querySelector('[class^="card-vote"]');
        const wbproTags = item.querySelectorAll(".wbpro-tag");
        const recommendTag = wbproTags
          ? Array.from(wbproTags).find(
              (tag) =>
                tag.textContent &&
                (tag.textContent.includes("推荐") || tag.textContent.includes("荐读"))
            )
          : null;

        const bloggerTitle = item.querySelector('[class^="title_title_"]');
        const isBloggerRecommend =
          bloggerTitle && bloggerTitle.textContent.includes("你常看的优质博主");

        if (voteElement || recommendTag || isBloggerRecommend) {
          if (voteElement) stats.votes++;
          if (recommendTag) stats.recommends++;
          if (isBloggerRecommend) stats.bloggers++;
          item.remove();
        }
      });

      if (stats.votes || stats.recommends || stats.bloggers) {
        console.log(
          `[weibo-cleaner] 已移除: ${stats.votes}个投票, ${stats.recommends}个推荐/引荐, ${stats.bloggers}个你常看的优质博主`
        );
      }
    } catch (error) {
      console.error("[weibo-cleaner] 清理过程中出错:", error);
    }
  }

  // Debounced filter function
  const debouncedClean = debounce(filterSpamItems, 300);

  // 观察DOM变化
  function observeDOM() {
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.addedNodes.length) {
          debouncedClean();
        }
      });
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    // Initial filtering
    debouncedClean();
  }

  // 页面加载完成后开始观察
  if (document.readyState === "complete" || document.readyState === "interactive") {
    observeDOM();
  } else {
    window.addEventListener("DOMContentLoaded", observeDOM);
  }
})();