Skip to content

Instantly share code, notes, and snippets.

@hungdoansy
Last active September 15, 2020 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hungdoansy/966df848fddecc47696e0ec38b77c68d to your computer and use it in GitHub Desktop.
Save hungdoansy/966df848fddecc47696e0ec38b77c68d to your computer and use it in GitHub Desktop.
User script used in TamperMonkey to remove ads in Facebooks' news feed | Currently, working with the new theme in English
// ==UserScript==
// @name Hide sponsored items
// @namespace whatisthis
// @version 0.1
// @description try to sanitize Facebook
// @author Sy Hung Doan
// @match https://www.facebook.com/*
// @match https://facebook.com/*
// @grant none
// ==/UserScript==
(function () {
// src: https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf
const throttle = (func, limit) => {
let lastFunc;
let lastRan;
return function () {
const context = this;
const args = arguments;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function () {
if (Date.now() - lastRan >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
};
let lastCommitIndex = 0;
let unitsContainer = document.querySelector("div[role='feed']");
const callback = () => {
unitsContainer = document.querySelector("div[role='feed']");
if (!unitsContainer) {
return;
}
const feedUnits = Array.from(
document.querySelectorAll(
`div[role='feed'] > div[data-pagelet^='FeedUnit_']:nth-child(n+${lastCommitIndex})`
)
);
if (!feedUnits.length) {
return;
}
Array(feedUnits.length)
.fill(0)
.forEach((_, i, obj) => {
const unit = feedUnits[i];
if (unit.querySelector("[aria-label='Sponsored']")) {
unitsContainer.removeChild(unit);
obj.splice(i, 1);
} else {
lastCommitIndex = i;
}
});
};
const callbackThrottled = throttle(callback, 1000);
const observer = new MutationObserver(callbackThrottled);
observer.observe(unitsContainer, { childList: true });
})();
@masterchop
Copy link

masterchop commented Sep 13, 2020

Thank you, this works with the new facebook theme that broke the old ones.

@hungdoansy
Copy link
Author

Thank you, this works with the new facebook theme that broke the old ones.

Glad that it helped you. I know there may be some bugs hidden somewhere and the performance doesn't seem like very good. I'll improve it on the way :D

@masterchop
Copy link

yes, i notice that but its good enough. ill keep an eye on this repo to see all your updates :)

@hungdoansy
Copy link
Author

yes, i notice that but its good enough. ill keep an eye on this repo to see all your updates :)

Thanks 🤓

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