Skip to content

Instantly share code, notes, and snippets.

@phocks
Last active March 1, 2024 00:41
Show Gist options
  • Save phocks/f4b5a024d6c1bf4bf48e604706757ed2 to your computer and use it in GitHub Desktop.
Save phocks/f4b5a024d6c1bf4bf48e604706757ed2 to your computer and use it in GitHub Desktop.
Paste into console to block advertisers on Twitter
// ==UserScript==
// @name Twitter Advertiser Blocker
// @namespace http://phocks.org
// @version 0.2.0
// @description Blocks advertisers on Twitter as you scroll
// @author @[email protected]
// @match https://twitter.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=twitter.com
// @grant none
// @license MIT
// ==/UserScript==
(function () {
"use strict";
let blockedCount = 0;
function blockAdvertiser() {
const spans = document.querySelectorAll("span");
let btn = null;
for (let span of spans) {
if (
span.textContent.includes("Promoted") ||
span.textContent.includes("Promoted by")
) {
// Are we sure it's not just a tweet that says "Promoted"??
// Let's try to be more sure. Check for svg promoted icon.
const divPromoted = span.parentNode.parentNode;
const svgPromoted = divPromoted.querySelector(
'svg[viewBox="0 0 24 24"]'
);
if (!svgPromoted) continue;
const svgShape = divPromoted.querySelector(
'[d="M19.498 3h-15c-1.381 0-2.5 1.12-2.5 2.5v13c0 1.38 1.119 2.5 2.5 2.5h15c1.381 0 2.5-1.12 2.5-2.5v-13c0-1.38-1.119-2.5-2.5-2.5zm-3.502 12h-2v-3.59l-5.293 5.3-1.414-1.42L12.581 10H8.996V8h7v7z"]'
);
if (!svgShape) continue;
btn = span;
break;
}
}
if (!btn) return;
const pnt = btn.closest("article");
if (!pnt) return;
const someSpans = pnt.querySelectorAll("span");
someSpans.forEach((span) => {
if (span.textContent.includes("@")) console.log(span.textContent);
});
const more = pnt.querySelector('[role="button"]');
more.click();
const block = document.querySelector('[data-testid="block"]');
block.click();
const confirm = document.querySelector(
'[data-testid="confirmationSheetConfirm"]'
);
confirm.click();
blockedCount++;
console.log("Advertisers blocked:", blockedCount);
}
setInterval(() => {
blockAdvertiser();
}, 1000);
})();
@smile-and-the
Copy link

Twitter's created a response to your script by automatically pushing a popup saying "only premium users deserve an ad-free experience"

I don't need you to update your script, but it would be nice!

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