How to create a mutation observer to remove all coming audio tags?

I tried to use the following userscript to remove all audio from a certain website:

// ==UserScript==
// @name        addicto
// @namespace   nms
// @include     http://*
// @include     https://*
// @version     1
// @grant       none
// ==/UserScript==

addEventListener('DOMContentLoaded', ()=>{
  let sites = ['mako.co.il'];
  for (let i = 0; i < sites.length; i++) {
    if (href.includes(sites[i])) {
      Array.prototype.slice.call(document.querySelectorAll('audio')).forEach((audio)=>{
        audio.muted = true;
      });
    }
  }

  // If href includes the value of the iteration on the "sites" array, do stuff.
});

This code didn’t work and I assume that observing all audio tags coming randomly and mutating the DOM is exactly what I need to better cope with this.

How can this mutation observer be written? I have never written a mutation observer and I feel as if this example would be very short and very basic and exactly what I need to get a taste of the code context of the logic which I just described and I would thank dearly to anyone who will try to show it to me and the students.

Here you go:

// The observer callback receives an array of 
// mutation records, over which we want to iterate
const forEachRecord = func => 
  records => 
    records.forEach(func)

// Each such record holds a node list of added nodes, 
// over which we also want to iterate
const forEachAddedNode = func => 
  ({ addedNodes }) => 
    Array.from(addedNodes).forEach(func)

// And we want to remove those nodes if they are audio elements
const removeAudioElement = node => node instanceof Audio && node.remove()

// The mutation observer gets instantiated with a callback...
const observer = new MutationObserver(
  forEachRecord(
    forEachAddedNode(
    	removeAudioElement)))

// ... and registered with the DOM element to observe 
// -- in this case, the entire body -- and a config object: 
// we want to get informed about mutations of the target's 
// child list as well as those of the its descendants
observer.observe(document.body, {
  childList: true,
  subtree: true
})

As always, check out the MDN for details!

1 Like

Note, I forgot to add the variable let href = window.location.href; to the original question.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.