9、chrome拓展使用动态注入去除页面元素

一、完整代码

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"
	},
	"options_ui":
	{
		"page": "options.html",
		"chrome_style": true
	},

	"background":
	{
		"scripts": ["js/background.js"],
		"persistent": true
	},
	"content_scripts": 
	[
		{
			"matches": ["*://*/*"],
			"js": ["jquery-1.8.3.js","js/content-scripts.js"],
			"run_at": "document_start",
			"all_frames":true
		}
		
	],
	"permissions":["tabs", "http://*/*", "https://*/*","storage"],
	"browser_action":{
		"default_popup": "popup.html"
	},
	"options_ui":
	{
		"chrome_style": true
	}
}

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/popup.css">

</head>
<body>

<header><h3 class="fonts">Filter Elements</h3></header>
<div class="main fonts border-style">
    <div class="contain" id="tag-contain">
        <label for="img" class="ad">img:
            <input type="checkbox" id="img" class="ad-style" >
        </label>
        <label for="video" class="ad">video:
            <input type="checkbox" id="video" class="ad-style">
        </label>
        <label for="iframe" class="ad">iframe:
            <input type="checkbox" id="iframe" class="ad-style">
        </label>
        <label for="a" class="ad">a:
            <input type="checkbox" id="a" class="ad-style">
        </label>
        <br>
        <label for="tag" class="ad">tag: <input type="text" id="tag"></label>
        <button type="submit" class="btn" id="tagAdd">add</button>
    </div>

    <div class="contain" id="id-contain">
        <label for="elementId" class="ad">id:  <input type="text" id="elementId"></label>
        <button type="submit" class="btn"  id="idAdd">add</button>
    </div>
    <div class="contain" id="class-contain">
        <label for="classId" class="ad">class:  <input type="text" id="classId"></label>
        <button type="submit" class="btn" id="classAdd">add</button>
    </div>
    <div class="btn-contain"> <button id="start">start</button>
        <button id="reset">reset</button>
    </div>

</div>

<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript" src="js/popup.js"></script>
</body>
</html>

popup.js


$('#idAdd').click(function (){
    if($('#elementId').val() !== '') {
        let data = $('#elementId').val()
        $('#id-contain').append(`<div class="taglist border-style">${data}</div>`);
    }
})
$('#classAdd').click(function (){
    if($('#classId').val() !== '') {
        let data = $('#classId').val()
        $('#class-contain').append(`<div class="taglist border-style">${data}</div>`);
    }
  })
$('#tagAdd').click(function (){

    if($('#tag').val() !== '') {
        let data = $('#tag').val()
         $('#tag-contain').append(`<div class="taglist border-style">${data}</div>`);
    }
  })

$('#start').click(function (){

    let tagArray = [];
    let idArray = [];
    let classArray = [];
    $('input:checkbox:checked').each(function (){
            tagArray.push($(this).attr('id'));
        });
    $('#tag-contain .taglist').each(function (){
        tagArray.push($(this).text())
    });
    $('#id-contain .taglist').each(function (){
        idArray.push($(this).text())
    })
    $('#class-contain .taglist').each(function (){
        classArray.push($(this).text())
    })
    if(tagArray.length){
        chrome.storage.sync.set({'tag': tagArray}, function() {
            console.log('success!');
        });
    }
   if(idArray.length){
       chrome.storage.sync.set({'id': idArray}, function() {
           console.log('success!');
       });
   }
  if(classArray.length){
      chrome.storage.sync.set({'class': classArray}, function() {
          console.log('success!');
      });
  }
    var bg = chrome.extension.getBackgroundPage();
    bg.getCurrentTabId();
})
$('#reset').click(function (){
    chrome.storage.sync.clear(function (){
        console.log('clear!');
        location.reload();
    })

})

excute.js

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

function isIn(args, arr) {
    let flag = false;
    for (let i in arr) {
        if (args === arr[i]) {
            flag = true;
            break;
        }
    }
    return flag;
}

function filter(tagArr, idArr, classArr) {
    const defaultTag = ['img', 'a', 'video', 'iframe'];
    if (tagArr !== undefined) {
        for (let j of tagArr) {
            if (isIn(j, defaultTag) === true) {
                for (let i of document.getElementsByTagName(j)) {
                    if (i.src && new RegExp(location.origin).test(i.src) === false) {
                        // let element = getElement(i);
                        // element.remove();
                        i.remove();
                    } else if (i.href !== "javascript:;" && (new RegExp(location.origin).test(i.href) === false)) {
                        // let element = getElement(i);
                        // element.remove();
                        i.remove();
                    }
                }
            } else {
                for (let i of document.getElementsByTagName(j)) {
                    i.remove()
                }
            }
        }
    }

    if (idArr !== undefined) {
        for (let j of idArr) {
            document.getElementById(j).remove();
        }
    }

    if (classArr !== undefined) {
        for (let j of classArr) {
            for(let i of document.getElementsByClassName(j)){
                i.remove();
            }
        }
    }
}


chrome.storage.sync.get(['tag', 'id', 'class'], function (items) {
    filter(items.tag, items.id, items.class)
})

background.js


function getCurrentTabId()
{
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs)
    {
        if(tabs.length){
            chrome.tabs.executeScript(tabs[0].id,{file:'js/excute.js'})
        }
    });
}


popup.css

body{
    background-color: whitesmoke;
    margin-left: 0px;
    margin-right: -2px;
}
.contain{
    width: auto;
    height: 20%;
    padding: 15px;
    background-color: white;
    margin: 15px;
    overflow:auto;
    line-height: 30px;
}
h3{
    text-align: center;
    padding: 8px;
    margin-top: -6px;
}
.fonts{
    font-size: 16px;
    font-family: "Goudy Old Style", fantasy;
}
header{
    height: 10%;
    width: 480px;
    background-color: skyblue;
}
.main{
    width: 480px;
    height: 460px;
    margin-bottom: -8px;
}
.taglist{
    display: inline;
    margin: 4px;
    background-color: lightcyan;
    line-height: 6px;
    word-break: break-all;
}
.btn{
    width: 60px;
}
#start,#reset{
    width: 200px;
    margin: 3px 9px ;
    height: 20px;
    display: inline;
}
.btn-contain{
    width: auto;
    height: 5%;
    padding: 5px;
    background-color: white;
    margin-top: -3px;
    margin-left: 15px;
    margin-right: 15px;
}
.ad{
    margin-left: 20px;
    padding-left: 15px;
}

.border-style{
    border-width: 1px;
    border-color: lightgray;
    border-style: solid;
    border-radius: 4px;
}

github:https://github.com/wxwcd/del_elementshttps://github.com/wxwcd/del_elements

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值