油猴-百度贴吧PC去广告

161 阅读1分钟
// ==UserScript==
// @name         贴吧去广告
// @namespace    http://tampermonkey.net/
// @version      2025-07-09
// @description  try to take over the world!
// @author       Feliks9527
// @match        https://tieba.baidu.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=baidu.com
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  window.onload = function () {
    function removeAllGG() {
      let headGG = document.querySelector(".plat_recom_carousel");
      let ggList = document.querySelectorAll(".ylh-ad-wrap");
      let ggList2 = document.querySelectorAll(".ylh-ad-container");
      let topCarousel = document.querySelector("#rec_left");
      let rightGG = document.querySelector(".r-right-sec");

      // 移除广告元素
      ggList.forEach(ad => {
        if (ad && ad.parentNode) {
          ad.parentNode.removeChild(ad);
        }
      });

      ggList2.forEach(ad => {
        if (ad && ad.parentNode) {
          ad.parentNode.removeChild(ad);
        }
      });

      if (headGG && headGG.parentNode) {
        headGG.parentNode.removeChild(headGG);
        console.log("==========去除头部广告");
      }

      if (topCarousel && topCarousel.parentNode) {
        topCarousel.parentNode.removeChild(topCarousel);
        console.log("==========去除顶部轮播");
      }

      if (rightGG && rightGG.parentNode) {
        rightGG.parentNode.removeChild(rightGG);
        console.log("==========去除右侧广告");
      }
    }

    // 页面加载时立即执行一次
    removeAllGG();

    // 定期检查并移除新出现的广告
    setInterval(() => {
      removeAllGG();
    }, 2000);

    // 监听URL变化(适用于单页应用)
    window.addEventListener('popstate', () => {
      console.log("URL变化");
      setTimeout(removeAllGG, 500); // 延迟执行,等待新内容加载
    });

    // 监听hash变化
    window.addEventListener('hashchange', () => {
      console.log("Hash变化");
      setTimeout(removeAllGG, 500);
    });

    // 使用MutationObserver监听DOM变化
    const observer = new MutationObserver((mutations) => {
      let shouldRemove = false;
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
          // 检查是否有新的广告元素添加
          mutation.addedNodes.forEach((node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              if (node.classList && (
                node.classList.contains('ylh-ad-wrap') ||
                node.classList.contains('ylh-ad-container') ||
                node.classList.contains('plat_recom_carousel') ||
                node.classList.contains('r-right-sec') ||
                node.id === 'rec_left'
              )) {
                shouldRemove = true;
              }
            }
          });
        }
      });

      if (shouldRemove) {
        setTimeout(removeAllGG, 100);
      }
    });
    observer.observe(document.body, {
      childList: true,
      subtree: true
    });
  };
})();