如何仅使用 JavaScript 轻松阻止 Facebook“广告”出现在 Feed 中?

问题描述 投票:0回答:1

在 Facebook feed 上滚动时,有大量“建议”和“赞助”帖子...任何人都可以找到一种简单而巧妙的方法来仅使用 JavaScript 来阻止它们出现?

这是我想出的解决方案,请随意使用/修改并提出任何改进建议!预先感谢您。

/*
   When scrolling through the facebook feed, if the mouse will be over
   a sponsored or a suggested for you post, the post will be removed (hidden)
   from the HTML page.
   
   HOW TO USE:
   Log into facebook, open the console of the browser (developer tools) and
   copy and paste and run the below code. THEN, write adBlocker.start() and
   hit [ENTER] to start and adBlocker.stop() followed by [ENTER] to stop it.
*/

adBlocker = {}
adBlocker.toRemoveDivs = [];

// the direct descendant child <div> of the <div> having the
// attribute role="feed" is the main parent div for the href link
adBlocker.postsContainerDIV = document.querySelector('div[role="feed"]>div');

// from: https://stackoverflow.com/questions/22119673/find-the-closest-ancestor-element-that-has-a-specific-class
adBlocker.findAncestor = function (el, sel) {
    while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
    return el;
}

adBlocker.scanForSponsoredDivs = function() {
    document.querySelectorAll('a[aria-label="Sponsored"]')
        .forEach(
            aHrefElement => adBlocker.toRemoveDivs.push( adBlocker.findAncestor( aHrefElement, 'div[data-pagelet^="FeedUnit_"]' ) )
        )
}

adBlocker.scanForSuggestedDivs = function() {
    document.querySelectorAll('span.x193iq5w.xeuugli.x13faqbe.x1vvkbs.x10flsy6.x1lliihq.x1s928wv.xhkezso.x1gmr53x.x1cpjm7i.x1fgarty.x1943h6x.x4zkp8e.x41vudc.x6prxxf.xvq8zen.xo1l8bm.xi81zsa[dir="auto"]')
        .forEach( function( span ) {
            if (span.innerHTML === "Suggested for you")
                adBlocker.toRemoveDivs.push( adBlocker.findAncestor( span, 'div[data-pagelet^="FeedUnit_"]' ) )
        })
}

adBlocker.isItASuggestedDiv = function(div) {
    span = div.querySelectorAll('span.x193iq5w.xeuugli.x13faqbe.x1vvkbs.x10flsy6.x1lliihq.x1s928wv.xhkezso.x1gmr53x.x1cpjm7i.x1fgarty.x1943h6x.x4zkp8e.x41vudc.x6prxxf.xvq8zen.xo1l8bm.xi81zsa[dir="auto"]')[0];
    return (span && span.innerHTML && span.innerHTML==="Suggested for you");
}

adBlocker.isItASponsoredDiv = function(div) {
    aHref = div.querySelectorAll('a[aria-label="Sponsored"]')[0];
    return aHref ? true : false;
}

adBlocker.hide = function( div ) {
    if ( div && div.style ) div.style.display = "none";
}

adBlocker.removeDivs = function() {
    for (div of adBlocker.toRemoveDivs) {
        // remove sponsoredDiv div from the facebook feed
        // adBlocker.postsContainerDIV.removeChild( div ); // this would again trigger MutationObserver...
        // to avoid triggering mutationObserver, we just hide the DIV
        adBlocker.hide( div );
        
        // remove DIV from the array of toRemoveDivs
        index = adBlocker.toRemoveDivs.indexOf( div );
        adBlocker.toRemoveDivs.splice( index, 1 );
    }
}

adBlocker.searchAndRemoveDivs = function() {
  adBlocker.scanForSponsoredDivs();
  adBlocker.scanForSuggestedDivs();
  adBlocker.removeDivs();
}

// from https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// Options for the observer (which mutations to observe)
adBlocker.observer_config = { childList: true };

// Callback function to execute when mutations are observed
adBlocker.observerCallback = (mutationList, observer) => {
  for (mutation of mutationList) {
    if (mutation.addedNodes.length > 0) {
      for (div of mutation.addedNodes) {
        if ( adBlocker.isItASuggestedDiv( div ) ||
             adBlocker.isItASponsoredDiv( div ) )
            adBlocker.hide( div );
      }
    }
  }
};

// Create an observer instance linked to the callback function
adBlocker.observer = new MutationObserver( adBlocker.observerCallback );

adBlocker.start = function() {
    console.log("adBlocker: Starting up...");
    
    // Since facebook has already loaded some posts into the feed,
    // remove any sponsored and suggested ones...
    console.log("adBlocker: Removing ads already loaded into your feed.");
    adBlocker.searchAndRemoveDivs();
    
    // Start observing the posts container for any changes, like,
    // if user scrolls and more posts are being loaded and further
    // remove any sponsored and suggested DIVs
    console.log("adBlocker: Setting up dynamic load observer for future ads.");
    adBlocker.observer.observe( adBlocker.postsContainerDIV, adBlocker.observer_config );
    console.log("adBlocker: All done, happy scrolling, ad free - no suggested for you and no sponsored posts either! :D");
}

adBlocker.stop = function() {
    adBlocker.observer.disconnect();
    console.log("adBlocker: Service NOW stopped! (use adBlocker.start() to restart it again)");
}
javascript facebook ads
1个回答
0
投票

一段时间后,Facebook feed 的 DOM 及其帖子发生了一些变化,一些为您推荐的帖子以及一些赞助帖子通过了 adBlocker javascript。

因此,我花了更多时间查看这些更改,并提出了上述代码的更好、更简单的变体。随意使用它! :) 并提出任何改进意见!

/*
   Version 2.0
   
   When scrolling through the facebook feed, any posts that are suggested
   or sponsored will be hidden from sight, hence, it's like they were
   never there in the first place!
   
   HOW TO USE:
   Log into facebook, open the console of the browser (developer tools)
   and copy and paste and run the below code. THEN, write
   adBlocker.start() and hit [ENTER] to start and adBlocker.stop()
   followed by [ENTER] to stop it.
*/

adBlocker = {}

// the direct descendant child <div> of the <div> having the
// attribute role="feed" is the main parent div for the href link
adBlocker.postsContainerDIV = document.querySelector('div[role="feed"]>div');

adBlocker.hide = function(div) {
  if (div && div.style) div.style.display = "none";
}

adBlocker.isItASuggestedDiv = function(div) {
  allChildSpans = div.querySelectorAll("span");
  if (allChildSpans.length > 0) {
    let i = 0;
    while (i < allChildSpans.length)
      if (allChildSpans[i++].innerHTML === "Suggested for you") return true;
  }
  return false;
}

adBlocker.isItASponsoredDiv = function(div) {
  aHref = div.querySelectorAll('a[aria-label="Sponsored"]')[0];
  return aHref ? true : false;
}

//adBlocker.scanForSuggestedDivs = function() {
adBlocker.hideAlreadyLoadedUnwantedDivs = function() {
  // all already loaded posts (DIVs)
  allPostDivs = adBlocker.postsContainerDIV.querySelectorAll('div[data-pagelet^="FeedUnit_"]');

  if (allPostDivs.length > 0) {
    i = 0;
    while (i < allPostDivs.length) {
      if (adBlocker.isItASuggestedDiv(allPostDivs[i]) ||
          adBlocker.isItASponsoredDiv(allPostDivs[i]))
        adBlocker.hide(allPostDivs[i]);
      i++;
    }
  }
}

// from https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
// Options for the observer (which mutations to observe)
adBlocker.observer_config = {
  childList: true
};

// Callback function to execute when mutations are observed
adBlocker.observerCallback = (mutationList, observer) => {
  for (mutation of mutationList) {
    if (mutation.addedNodes.length > 0) {
      for (div of mutation.addedNodes) {
        if (adBlocker.isItASuggestedDiv(div) ||
            adBlocker.isItASponsoredDiv(div))
          adBlocker.hide(div);
      }
    }
  }
};

// Create an observer instance linked to the callback function
adBlocker.observer = new MutationObserver(adBlocker.observerCallback);

adBlocker.start = function() {
  console.log("adBlocker: Starting up...");
  // Since facebook has already loaded some posts into the feed,
  // remove any sponsored and suggested ones...
  console.log("adBlocker: Removing ads already loaded into your feed.");
  adBlocker.hideAlreadyLoadedUnwantedDivs();

  // Start observing the posts container for any changes, for ex.
  // if user scrolls and more posts are being loaded and further
  // remove any sponsored and suggested DIVs
  console.log("adBlocker: Setting up dynamic load observer for future ads.");
  adBlocker.observer.observe(adBlocker.postsContainerDIV, adBlocker.observer_config);
  console.log("adBlocker: All done, happy scrolling, ad free - no suggested for you and no sponsored posts either! :D");
}

adBlocker.stop = function() {
  adBlocker.observer.disconnect();
  console.log("adBlocker: Service NOW stopped! (use adBlocker.start() to restart it again)");
}

© www.soinside.com 2019 - 2024. All rights reserved.