繁体   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