Twitter as a platform is pretty neat. Twitter as a company sucks.
A while back they started blasting ads into my timeline, which is something I’m really not here for. I would gladly pay a fee not to have that because I love the platform, but y’know. Corporate bullshit etc. 🙄
So I’ve been taking it out on the advertisers audacious enough to target me, by blocking them. Apple? Blocked. Amazon? Blocked. Intel? You betcha you’re gonna git blocked.
Despite my best efforts it got to the point where I was getting way too many ads to keep up with, so I decided to write a script to do it automatically.
There’s an extension you can install to auto-block Twitter advertisers (providing you’re using the mobile site). You can get this for:
I mainly use the mobile Twitter site becuse it’s way faster than desktop, but it’s one of those sites that use React to munge class names. So instead of seeing nice
<div class="tweet"> HTML, you get something more akin to
<div class="rn-1oszu61 rn-1efd50x rn-14skgim rn-rull8r …]">
This makes it insanely difficult to automate the process of finding an ad and blocking it. I’m not sure what ad blockers are doing, but this requires some pretty specific DOM selection to get working.
There’s two approaches you could take:
- Loop through all the
<div>elements on the page until you find one with the text you’re looking for. Eg. “promoted”.
- Use weirdly specific selectors that get the job done, almost by chance.
Writing client-side code to automate tasks in a React app like Array.from(document.querySelectorAll('div'))— Ash Kyd (@AshKyd) May 26, 2018
.find(d => d.textContent === 'Yes')
Despite making fun on Twitter I chose the latter, because Twitter uses inline SVG elements, which means we can find promoted tweets by querying for the presence of certain SVG paths. It’s completely absurd and I think React is criminally negligent for making this a standard practice.
Here’s the two main selectors I’m using to find interface elements on Twitter mobile:
// The "promoted icon"
The remainder of the extension is fairly straightforward. Find stuff, click stuff, you know the deal. If you’re interested in having a play with it yourself, you can check it out and give it some stars on Github.