mfluehr / Mute Spotify Ads

// ==UserScript==
// @namespace     https://openuserjs.org/users/mfluehr
// @name          Mute Spotify Ads
// @description   Mute advertisements on Spotify.
// @license       MIT
// @version       1.0.0
// @match         *://*.spotify.com/*
// @run-at        document-start
// @grant         none
// ==/UserScript==

const $title = document.head.querySelector('title');
const observer = new MutationObserver(callback);

const observerOptions = {
  childList: true,
  attributes: false,
  subtree: true
}

observer.observe($title, observerOptions);

function callback(mutationList, observer) {
  mutationList.forEach((mutation) => {
    const text = mutation.addedNodes[0].nodeValue;

    if (text.startsWith('Advertisement')) {
      const $mute = document.querySelector('.spoticon-volume-16');
      $mute?.click();
    } else {
      const $unmute = document.querySelector('.spoticon-volume-off-16');
      $unmute?.click();
    }
  });
}