8、content-scripts实现一个简单的去除广告插件

一、测试网址 https://www.yy6080.info/

manifest.json

{
	"manifest_version": 2,
	"name": "NoAd",
	"version": "1.0.0",
	"description": "",
	"icons":
	{
		"16": "icon/icon.png",
		"48": "icon/icon.png",
		"128": "icon/icon.png"
	},

	"content_scripts": 
	[
		{
			"matches": ["*://www.yy6080.info/*"],
			"js": ["js/content-scripts.js"],
			"run_at": "document_end",
			"all_frames":true
		}
		
	],
	"permissions":["*://www.yy6080.info/*"],
	"browser_action":{},
	"options_ui":
	{
		"chrome_style": true
	}
}

二、content-scripts

function getElement(element) {
    if (element.parentElement === document.body ) {
        return element
    } else
        return getElement(element.parentElement)
}

function filter() {
    for (let i of document.getElementsByTagName('a')) {
        if (i.href !== "javascript:;" && new RegExp(location.origin).test(i.href) === false) {
            let element = getElement(i);
			if(element.className !== "container"){
                element.remove();
            }
        }

    }
    for (let i of document.getElementsByTagName('img')) {
        if (new RegExp(location.origin).test(i.src) === false) {
			console.log(new RegExp(location.origin).test(i.src))
			let element = getElement(i);
            if(element.className !== "container"){
                element.remove();
            }
        }
    }
    for (let i of document.getElementsByTagName('video')) {
		console.log(new RegExp(location.origin).test(i.src))
		if (new RegExp(location.origin).test(i.src) === false) {
            let element = getElement(i);
            if(element.className !== "container"){
                element.remove();
            }
        }
    }
    for (let i of document.getElementsByTagName('iframe')) {
		console.log(new RegExp(location.origin).test(i.src))
		if (new RegExp(location.origin).test(i.src) === false) {
            let element = getElement(i);
            if(element.className !== "container"){
                element.remove();
            }
        }
    }
}
    window.onload = function () {
        filter();
    }

这种方式在触犯onload事件后,对含有广告的块级元素进行移除,也就是说在触发onload之前,网址上还是可以看到广告的,目前这段代码只能在https://www.yy6080.info/这个网址中用,其他网址要根据其实际情况进行修改

三、去广告前

 四、去广告后

 

你可能感兴趣的:(Chrome使用,content-scripts,chrome插件去广告)