Remove sponsored posts from Reddit

Removes sponsored posts from Reddit using modern DOM observation.

이 스크립트를 설치하려면 Tampermonkey, Greasemonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

You will need to install an extension such as Tampermonkey to install this script.

이 스크립트를 설치하려면 Tampermonkey 또는 Violentmonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey 또는 Userscripts와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 Tampermonkey와 같은 확장 프로그램이 필요합니다.

이 스크립트를 설치하려면 유저 스크립트 관리자 확장 프로그램이 필요합니다.

(이미 유저 스크립트 관리자가 설치되어 있습니다. 설치를 진행합니다!)

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 Stylus와 같은 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

이 스타일을 설치하려면 유저 스타일 관리자 확장 프로그램이 필요합니다.

(이미 유저 스타일 관리자가 설치되어 있습니다. 설치를 진행합니다!)

// ==UserScript==
// @name         Remove sponsored posts from Reddit
// @namespace    https://github.com/b263/user-scripts
// @version      1.0.0
// @description  Removes sponsored posts from Reddit using modern DOM observation.
// @author       Bastian Bräu
// @match        https://www.reddit.com/*
// @grant        none
// @license      ISC
// @homepageURL  https://github.com/b263/user-scripts
// @supportURL   https://github.com/b263/user-scripts/issues
// ==/UserScript==

const AD_CONTAINER = 'shreddit-ad-post';

let observer = null;

function removeAds() {
  const ads = document.querySelectorAll(AD_CONTAINER);
  ads.forEach(ad => {
    try {
      ad.remove();
    } catch (error) {}
  });
}

function shouldProcessMutation(mutation) {
  if (mutation.type !== 'childList' || mutation.addedNodes.length === 0) {
    return false;
  }

  return Array.from(mutation.addedNodes).some(node => {
    if (node.nodeType !== Node.ELEMENT_NODE) return false;

    if (node.matches?.(AD_CONTAINER)) {
      return true;
    }

    if (node.querySelector) {
      return !!node.querySelector(AD_CONTAINER);
    }

    return false;
  });
}

function handleMutations(mutations) {
  const relevantMutations = mutations.filter(mutation =>
    shouldProcessMutation(mutation)
  );

  if (relevantMutations.length > 0) {
    removeAds();
  }
}

function setupObserver() {
  observer = new MutationObserver(handleMutations);

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

function init() {
  removeAds();
  setupObserver();
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}