Skip to content

Instantly share code, notes, and snippets.

@mikhasd
Last active June 30, 2023 07:58
Show Gist options
  • Save mikhasd/6bc0a0d51810751bf49594bf36f3208f to your computer and use it in GitHub Desktop.
Save mikhasd/6bc0a0d51810751bf49594bf36f3208f to your computer and use it in GitHub Desktop.
Tampermonkey user script to Block/Remove Ads from Facebook timeline - Working as of 28-10-2021
// ==UserScript==
// @name Remove Facebook Ads
// @namespace https://gist.github.com/mikhasd
// @version 0.1
// @description Tampermonkey user script to remove ads from Facebook timeline.
// @author mikhasd
// @match https://www.facebook.com/
// @icon https://www.google.com/s2/favicons?domain=facebook.com
// @grant none
// ==/UserScript==
const TAG = '[TAMPERMONKEY]'
async function timeout(time){
return new Promise(resolve => {
setTimeout(resolve, time)
})
}
async function findFeedRoot(){
while(true){
let feed = document.querySelector('div[role=feed]')
if(feed){
return Promise.resolve(feed)
}
await timeout(10)
}
}
(async function() {
'use strict';
console.info(TAG, 'initializing Remove Facebook Ads')
const feed = await findFeedRoot()
console.info(TAG, 'acquired feed element')
function findFeedElement(a){
let el = a.parentElement
while(el.parentElement != feed){
el = el.parentElement
}
return el
}
function cleanAds(){
const start = performance.now()
const ads = Array.from(feed.querySelectorAll('a[role][aria-label] > span > span span'))
.filter(span => span.innerText[0] == 'S')
.filter(span => {
const style = window.getComputedStyle(span)
return style.position === 'relative' && style.display === 'inline'
})
const count = ads.length
if (count == 0 ){
return
}
ads.map(findFeedElement)
.forEach(el => {
try{
el.remove()
} catch (e){}
})
const end = performance.now()
console.info(TAG, `removed ${count} ads in ${end - start}ms`)
}
const observer = new MutationObserver(cleanAds)
observer.observe(feed, {
subtree: true,
childList: true,
attributes: false
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment