2

I'm writing a chrome extension intended to hide videos from specified channels on youtube.

The solution I'm using right now looks like this:

var previousRendererAmount = 0;
window.setInterval( function() {
  var currentRendererAmount = $(removableRendererNameString).length;
  // Check if renderer amount har changed since last time (If not, we don't need to run the removal script.)
  if( currentRendererAmount != previousRendererAmount) {
    previousRendererAmount = currentRendererAmount;
    removeVideos();
  }
}, 20);

Simply put it's run at intervals of 20 milliseconds and does a check to see if video thumbnails shown has changed. If it has it runs the removal script.

But what I really want to do is to remove them before they are displayed. Something like an event handler triggered when the DOM element(and it's children) is created. Is this possible?

1 Answer 1

1

Yes, it is possible. You can use MutationObserver to add callback, when some DOM element changes. Check this page with example: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

In my example you can see that code within callback is executed before new element is added. That means you can delete unwanted elements before they are displayed.

let btn = document.getElementById('btn');
let videos = document.getElementById('videos');
let nodeToAdd = document.createElement('div');
nodeToAdd.innerText = 'Video 3';

btn.addEventListener('click', function() {
  videos.appendChild(nodeToAdd);
  btn.parentNode.removeChild(btn);
});

let observer = new MutationObserver(
function(mutationsList) {
  for(let mutation of mutationsList) {
    if (mutation.type == 'childList') {
      alert('Hey, this msg is displayed first');
    }
  }
});

observer.observe(videos, {childList: true});
<div id='videos'>
  <div>Video 1</div>
  <div>Video 2</div>
</div>

<button id='btn'>Add Video 3</button>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It works really well. The only thing still is that the first elements that appear on load flashes quickly. Probably because I don't call the .observe early enough. Problem is I need an element to call it on (body for example). So I have to make sure body is created before I call it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.