Skip to content

Instantly share code, notes, and snippets.

@marcbelmont
Last active April 22, 2024 10:28
Show Gist options
  • Save marcbelmont/1ea63270867a4e8786dd5f172d8d4489 to your computer and use it in GitHub Desktop.
Save marcbelmont/1ea63270867a4e8786dd5f172d8d4489 to your computer and use it in GitHub Desktop.
Spotify Ad Muter. Automatically mute (block) Spotify ads. Turn sound on again after the ad.
// ==UserScript==
// @name Spotify Ad Muter
// @version 1.2
// @namespace http://tampermonkey.net/
// @description Detects and blocks ads on Spotify. Automatically mute Spotify ads. Turn sound on again after the ad.
// @match https://*.spotify.com/*
// @grant none
// @run-at document-start
// @downloadURL https://gist.github.com/marcbelmont/1ea63270867a4e8786dd5f172d8d4489/raw
// @updateURL https://gist.github.com/marcbelmont/1ea63270867a4e8786dd5f172d8d4489/raw
// ==/UserScript==
!async function () {
async function queryAsync(query) {
return new Promise(resolve => {
const interval = setInterval(() => {
const element = document.querySelector(query);
if (element) {
clearInterval(interval);
return resolve(element);
}
}, 250);
});
}
const nowPlayingBar = await queryAsync('[data-testid=now-playing-widget]');
const volumeButton = await queryAsync('button.volume-bar__icon-button');
const adQuerySelector = '[data-testid=now-playing-widget] *[aria-label~=Advertisement]';
let playInterval;
new MutationObserver(() => {
if (document.querySelector(adQuerySelector) &&
volumeButton.attributes['aria-label'].value.toLowerCase().indexOf('unmute') == -1) {
volumeButton.click();
if (!playInterval) {
playInterval = setInterval(() => {
if (!document.querySelector(adQuerySelector)) {
clearInterval(playInterval);
playInterval = null;
volumeButton.click();
}
}, 500);
}
}
}).observe(nowPlayingBar, {
characterData: true,
childList: true,
attributes: true,
subtree: true
});
}();
@RoguedBear
Copy link

spotify recently updated their UI, so the old element selector for now playing bar is not working.

I have updated the selector for nowPlayingBar and adQuerySelector and can confirm from my side the script is muting the ads and unmuting them afterwards

-    const nowPlayingBar = await queryAsync('.Root__now-playing-bar');
+    const nowPlayingBar = await queryAsync('[data-testid=now-playing-widget]');
     const volumeButton = await queryAsync('button.volume-bar__icon-button');
-    const adQuerySelector = '.Root__now-playing-bar *[aria-label~=Advertisement]';
+    const adQuerySelector = '[data-testid=now-playing-widget] *[aria-label~=Advertisement]';

@marcbelmont
Copy link
Author

@RoguedBear thanks for feedback. I'm updating it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment