2017-06-05 50 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

相關問題