Last active
August 9, 2023 13:17
-
-
Save tizee/b80c4f56770b96d848eade5f4357a96d to your computer and use it in GitHub Desktop.
Twitter promoted tweets blocker for Tampermonkey
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Twitter promoted blocker | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Block twitter promoted tweets at home timeline | |
// @author tizee | |
// @match https://twitter.com/* | |
// @icon https://www.google.com/s2/favicons?sz=64&domain=twitter.com | |
// @grant none | |
// ==/UserScript== | |
(function () { | |
"use strict"; | |
const hiddenTweets = new WeakSet(); | |
function watchTweetNodes(mutationList) { | |
mutationList.forEach(function (mutationRecord) { | |
mutationRecord.addedNodes.forEach(function (node) { | |
if (node && typeof node.querySelector == "function") { | |
const tweet = node.querySelector( | |
`div[data-testid="cellInnerDiv"] article[data-testid="tweet"]` | |
); | |
if (tweet) { | |
if (hiddenTweets.has(tweet)) { | |
return; | |
} | |
const spans = tweet.querySelectorAll("span"); | |
if ( | |
[...spans] | |
.map((span) => span.innerHTML) | |
.some((txt) => txt == "Promoted" || txt == "Ad") | |
) { | |
tweet.style.display = "none"; | |
console.debug("block promoted tweet", tweet); | |
hiddenTweets.add(tweet); | |
} | |
} | |
} | |
}); | |
}); | |
} | |
const regex = /^https:\/\/twitter.com\/.*$/; | |
const observer = new MutationObserver(function (mutationList, observer) { | |
if (!regex.test(window.location.href)) { | |
return; | |
} | |
watchTweetNodes(mutationList); | |
}); | |
observer.observe(document.documentElement, { | |
childList: true, | |
subtree: true, | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment