簡體   English   中英

使用javascript搜索帶有廣告服務器列表的文本文件

[英]Search a text file with list of ad servers in javascript

我正在制作一個阻止廣告的程序。 我在頁面上找到了廣告服務器列表。 我的問題:是否可以使用javascript從網站上的該頁面搜索這些廣告服務器? 請注意,我需要擴展代碼

默認情況下,網頁無法使用JavaScript訪問另一個網頁的內容。 這稱為跨域HTTP請求 該網站可以允許不同的網站使用HTTP標頭Access-Control-Allow-Origin訪問其內容,但是特別是您的頁面沒有這樣做。

如果繼續嘗試,將出現錯誤XMLHttpRequest cannot load https://pgl.yoyo.org/as/serverlist.php?hostformat=nohtml&showintro=1&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. XMLHttpRequest cannot load https://pgl.yoyo.org/as/serverlist.php?hostformat=nohtml&showintro=1&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

要解決此限制,您可以開發瀏覽器擴展,也可以使用crossorigin.me之類的代理。

這是一個工作示例:

 function loadAdServers(callback) { const url = 'https://crossorigin.me/https://pgl.yoyo.org/as/serverlist.php?hostformat=nohtml&showintro=1&startdate%5Bday%5D=&startdate%5Bmonth%5D=&startdate%5Byear%5D='; const request = new XMLHttpRequest(); request.open('GET', url); request.addEventListener('load', function () { callback(request.response.split('\\n').filter(x => x)); }); request.send(); } function removeElement(element) { if (element.parentElement) { element.parentElement.removeChild(element); } } function removeAdElements(adServers) { for (const img of document.querySelectorAll('img')) { for (const adServer of adServers) { if (img.src.indexOf(adServer) >= 0) { removeElement(img); } } } for (const a of document.querySelectorAll('a')) { for (const adServer of adServers) { if (a.href.indexOf(adServer) >= 0) { removeElement(a); } } } } loadAdServers(removeAdElements); 
  <img src="http://101order.com/company.logo"> <a href="http://101order.com/">Link</a> <a href="http://stackoverflow.com">stackoverflow</a> 

加載列表和過濾元素需要一些時間。

您可以使用以下方式:

var sites = ['site1', 'site2', '...'],
    sites_len = sites.length;
var els = document.getElementsByTagName('*');

for (var i = 0, len = els.length; i < len; i++) {
    var attr = "";
    switch (els[i].tagName.toLowerCase()) {
        case 'iframe':
        case 'script':
        case 'img':
            attr = 'src';
            break;
        case 'link':
        case 'a':
            attr = 'href';
            break
        default:
            continue;
    }
    var attr_val = els[i].getAttribute(attr);
    for (var j = 0; j < sites_len; j++)
        if (sites[j].indexOf(attr_val) > -1)
            els[i].parentNode.reamoveChild(els[i]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM