Skip to content

Instantly share code, notes, and snippets.

@theftprevention
Created February 7, 2019 04:15
Show Gist options
  • Save theftprevention/322592270c1a96d04be4a54640fcf926 to your computer and use it in GitHub Desktop.
Save theftprevention/322592270c1a96d04be4a54640fcf926 to your computer and use it in GitHub Desktop.
Hides all stories in the Facebook news feed except for sponsored advertisements. This is the antithesis to "remove-facebook-ads.js", as requested by /u/datlean.
// ==UserScript==
// @name Select Facebook Ads
// @version 1.0
// @description Hides all stories in the Facebook news feed except for sponsored advertisements.
// @author theftprevention
// @match https://www.facebook.com/
// @grant none
// ==/UserScript==
(function() {
'use strict';
var interval = 1000;
var reg_sponsored = /^Sponsored$/i;
var subtitleSelector = "[data-testid='story-subtitle'] > span:first-child";
var storySelector = "div[data-testid='fbfeed_story']";
var whitelist = new WeakSet();
/**
* @param {HTMLElement} element
* @returns {string}
*/
function getDisplayedInnerText(element) {
var style = getComputedStyle(element);
if (style.display === 'none') {
return '';
}
var child;
var children = element.childNodes;
var text = '';
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
switch (child.nodeType) {
case Node.ELEMENT_NODE:
text += getDisplayedInnerText(child);
break;
case Node.TEXT_NODE:
text += child.textContent;
break;
}
}
return text;
}
/**
* @returns {void}
*/
function selectAds() {
var element;
var elements = document.querySelectorAll(storySelector);
var i = elements.length;
var subtitle;
while (i--) {
element = elements[i];
if (whitelist.has(element)) {
continue;
}
whitelist.add(element);
subtitle = element.querySelector(subtitleSelector);
if (!subtitle || !reg_sponsored.test(getDisplayedInnerText(subtitle))) {
element.style.display = 'none';
}
}
}
/**
* @returns {void}
*/
function initialize() {
document.removeEventListener('DOMContentLoaded', initialize);
setInterval(selectAds, interval);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initialize);
} else {
initialize();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment