2017-06-05 56 views
-1

要阻止一个元素,可以使用:如何通过用户脚本方便地隐藏使用adblocker选择的元素?

var adSidebar = document.getElementById('ads'); 
if (adSidebar) { 
    adSidebar.parentNode.removeChild(adSidebar); 
} 

但这是一个具体元素,一个特定部位。要阻止多个站点中的多个元素,userscript必须多次使用@include,并且在每个站点中都应该多次列出元素。假设我有一个adblocker过滤器列表,如何方便地将其转换为单个的脚本?

www.youtube.com###watch7-sidebar-contents 
www.youtube.com##.yt-masthead-logo-container 
www.facebook.com##._1uh-:nth-of-type(2) 
www.facebook.com##._2t-e > ._4kny:nth-of-type(1) 
www.facebook.com##._1uh-:nth-of-type(1) 
www.facebook.com##._50tj._2t-a 
www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a 
www.facebook.com###u_0_0 
www.facebook.com###fbDockChatBuddylistNub > .fbNubButton 

我想保持在一个地方列表,因此,如果需要被阻塞在一个新的网站一个新的元素,我只是简单地从uBlock行添加到列表中。

+0

你必须为该列表编写解析器,或查找/修改现有的解析器。 – wOxxOm

+0

你为什么要这样做? –

回答

1

您可以通过创建一个在所有域上运行的用户脚本来解析从域的广告拦截器获取的字符串列表和查询选择器,查看它是否与窗口的域匹配以及是否存在元素,如果是的话就把它们删除。我提供了这样做下面的方法之一:

// ==UserScript== 
// @name   Custom element hider 
// @namespace https://zachsaucier.com/ 
// @version  0.1 
// @description To show how one can hide elements like an ad blocker using userscripts 
// @author  Zach Saucier 
// @match  *://*/* 
// @grant  none 
// ==/UserScript== 

(function() { 
    'use strict'; 

    // Set our list of sites and elements to block 
    var blockList = [ 
     "www.youtube.com###watch7-sidebar-contents", 
     "www.youtube.com##.yt-masthead-logo-container", 
     "www.facebook.com##._1uh-:nth-of-type(2)", 
     "www.facebook.com##._2t-e > ._4kny:nth-of-type(1)", 
     "www.facebook.com##._1uh-:nth-of-type(1)", 
     "www.facebook.com##._50tj._2t-a", 
     "www.facebook.com##._50ti._2s1y._5rmj._26aw._2t-a", 
     "www.facebook.com###u_0_0", 
     "www.facebook.com###fbDockChatBuddylistNub > .fbNubButton" 
    ]; 

    // Get the window's hostname 
    var windowHostname = window.location.hostname; 

    // Iterate through the blocklist, hiding elements as needed 
    for(var i = 0; i < blockList.length; i++) { 
     var entryParts = blockList[i].split('##'); 

     // Compare the hostnames; Only remove elements if they match 
     if(windowHostname === entryParts[0]) { 
      // Find the elements if they exists 
      var matchedElements = document.querySelectorAll(entryParts[1]); 

      // Actually remove the element(s) that match 
      for(var j = 0; j < matchedElements.length; j++) { 
       var matchedElem = matchedElements[j]; 

       matchedElem.parentNode.removeChild(matchedElem); 
      } 
     } 
    } 
})(); 

虽然我不知道你为什么会想要写一个userscript做到这一点时,广告拦截器本身可以做到这一点...

+0

@Ooker这是另一个问题;) –

+0

我知道,只是想通知的信息。非常感谢你为这些问题提供答案 – Ooker

相关问题