原因:每每在浏览网页的时候,都会碰到很多广告弹出,影响页面浏览,真是深恶痛绝,一直想能用什么方法可以屏蔽广告。后来发现chrome下可以自定义插件并且和页面进行交互,操作也挺简单的,所以便动手试试看。
一、chrome浏览器插件加载入口
“加载正在开发的扩展程序”:弹出对话框,手动加载自定义插件的文件夹,后面看。
“打包扩展程序”:用于将自定义插件进行打包,给其他人使用。
二、插件目录
三、步骤
1、新建配置文件清单manifest.json,内容如下:
{
"name": "清除广告插件",
"version": "1.0",
"description": "用于清除页面广告",
"author": "shizf",
"manifest_version": 2,
"browser_action": {
"default_icon": "icon.png",//插件图标
"default_popup": "popup.html"//浏览器插件弹出框
},
//匹配待注入页面并注入相应的css和js
"content_scripts": [
{
"matches": [
http://*/* //匹配所有站点
],
"css": [
"inject.css"//注入的css
],
"js": [
"inject.js"//注入的脚本
]
}
],
"permissions": [
"http://*/*"
]
}
2、新建popup.html 页面,用于显示插件弹出框:
【style.css 和index.js 为弹出框的样式和脚本,测试证明,此处的脚本不能够被执行】
<!doctype>
<html>
<head>
<title>清除广告插件</title>
<meta charset="utf-8"></meta>
<link rel="stylesheet" href="style.css">
<script src="index.js" type="text/javascript"></script>
</head>
<body>
<!--<div id="head">清除广告</div>-->
<div id="content">
<div>启用清除插件</div>
<div>本页不启用</div>
<div>3</div>
<div>4</div>
<div>5</div>
</div>
</body>
</html>
然后执行一中的“加载正在开发的扩展程序”,选中当前项目根目录,若顺利的话,将看到如下界面:
浏览器插件栏,将看到刚才自定义的插件,图标和弹出框。
3、后台交互页面
popup.html 不能够直接和页面进行交互,需要通过”background.html”作为中间人进行交互,所以popup.html页面的按钮操作记录可以通过本地存储的方案进行。
4、脚本注入:为所欲为
详见配置文件:
inject.js 和inject.css
找到对应站点的广告标签id 然后设置其css属性不可见既可以了。
console.log('%c chrome inject success', 'font-color:red;');//测试脚本是否注入成功
//超简单的对象选择器,没有引入jQuery
function $(obj) {
if (obj == null || obj == undefined || obj == "") {
return null;
}
switch (obj[0]) {
case "#":
return document.getElementById(obj.substr(1));
break;
case ".":
return document.getElementsByClassName(obj.substr(1));
break;
default:
return document.getElementsByTagName(obj);
break;
}
}
var currentUrl = window.location.href;
function indexOfUrl(src, dest) {
return src.indexOf(dest);
}
//清除电影天堂
(function () {
var url = window.location.href;
if (url.indexOf('http://www.dytt8.net/') > -1) {
if (url != 'http://www.dytt8.net/') {
$('#cs_left_couplet').style.display = "none";
$('#cs_right_couplet').style.display = "none";//
}
setTimeout(function () {
$('#MZADX_6628').innerHTML = "";
}, 3000);
$('#MZADX_4721').innerHTML = "";
}
})();
//清除http://k8yy.com/
(function () {
if (indexOfUrl(currentUrl, 'http://k8yy.com/') > -1) {
$('#__QY_CP_LEFT_Div').style.display = "none";
$('#__QY_CP_RIGHT_Div').style.display = "none";
}
})();
(function (dest) {
if (indexOfUrl(currentUrl, dest) > -1) {
if (currentUrl.length > dest.length) {
$('#BAIDU_UNION__wrapper_u1889509_0_left').style.display = 'none';
$('#BAIDU_UNION__wrapper_u1889509_0_right').style.display = 'none';
var list = $('.ad_336x280');
for (var index = 0; index < list.length; index++) {
list[index].style.display = 'none';
}
}
}
})('http://www.admin10000.com');
四、效果
访问任意站点页面,以http://www.admin10000.com/为例:
就是这么个屏幕,每次都让有强迫症的我,必须要把广告点掉,才会继续浏览文章。
来看一下清空之后的效果:
好了,以上是我简单的chrome去广告插件步骤和代码,具体代码下载请移步:https://github.com/Shizf/ClearAd
持续更新中。。。