Skip to content

Feat: Use MutationObserver #167

@hui1601

Description

@hui1601

현재는 다음과 같이 setInterval을 사용하여 1.5초마다 광고가 있는지 확인하는 방법을 사용하고 있습니다.

https://github.com/List-KR/NamuLink/blob/1470b49629b779ab3308b0e571c54a7aecd1f918/sources/src/index.ts#L82

하지만 파워링크 광고의 내용이 동적으로 로드되기에 MutationObserver을 활용하여, DOM에 insert되는 element를 감지, 광고를 제거할 수 있습니다.

다음은 개인적으로 사용하기 위해 만든 UserScript입니다. 개발에 도움이 되시면 좋겠습니다.

// ==UserScript==
// @name        NamuPower
// @namespace   Violentmonkey Scripts
// @match       https://namu.wiki/w/*
// @grant       none
// @version     1.0
// @author      -
// @description 9/6/2024, 8:46:51 PM
// @run-at      document-start
// ==/UserScript==


new MutationObserver(async (a, b) => {
  a.map(e => {
    if (e.addedNodes.length) {
      Array.from(e.addedNodes).map((e) => {
        const parent = e.parentElement;
        if(!parent) return;
        if(parent.tagName === 'DIV' && parent.className === '' && parent.parentElement.tagName === 'DIV') {
          const allElement = Array.from(parent.parentElement.querySelectorAll('span'));
          if(allElement.filter(e=>window.getComputedStyle(e,false).backgroundImage.startsWith('url("data:image/png;base64,')).length >= 2 || allElement.filter(e=>e.innerText==='파워링크').length !== 0){
            parent.parentElement.remove();
          }
        }
        // for mobile
        else if(e.tagName === 'SPAN' && parent.tagName === 'SPAN' &&parent.parentElement.tagName === 'DIV') {
          if(!e.querySelectorAll('img')) return;
          if(!Array.from(e.querySelectorAll('img')).filter(e=>e.style.color!=='').length){
            return;
          }
          // hide leftovers
          parent.parentElement.parentElement.parentElement.style['min-height'] = '0';
          parent.parentElement.parentElement.parentElement.style['height'] = '0';
          
          parent.parentElement.parentElement.remove();
        }
      });
    }
  });
}).observe(document, { subtree: true, childList: true });

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions