我创建了一个Chrome扩展程序,用于审查dom中的数据。它允许您向localStorage
添加关键字,然后隐藏这些关键字的父div,并使用删失的dom更新dom。
我的问题是如果在页面上添加关键字,它会起作用,并且该页面会立即更新。
但如果我转到新页面,我必须再次添加关键字。我需要在页面加载时使用已审查的dom更新查看的新选项卡,以减少用户执行任何操作的次数。
background.js
chrome.runtime.onMessage.addListener(function (msg, sender) {
// First, validate the message's structure
if ((msg.from === 'content') && (msg.subject === 'showPageAction')) {
// Enable the page-action for the requesting tab
chrome.pageAction.show(sender.tab.id);
}
});
function loadKeyWords() {
$('#keyWords').html('');
localArray = JSON.parse(localStorage.getItem('keyWords'));
for(var i = 0; i < localArray.length; i++) {
$('#keyWords').prepend('<li><input class="check" name="check" type="checkbox">'+localArray[i]+'</li>');
$( "div:contains("+localArray[i]+")" ).css( "display", "none" );
$( "section:contains("+localArray[i]+")" ).css( "display", "none" );
}
return localArray;
}
chrome.browserAction.onClicked.addListener(function(activeTab){
var newURL = "https://www.facebook.com/zensorship";
chrome.tabs.create({ url: newURL });
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var getKeywords = loadKeyWords();
chrome.tabs.executeScript(null, {
code: 'var config = ' + JSON.stringify(getKeywords)
}, function() {
chrome.tabs.executeScript(null, {file: 'custom.js'});
});
});
custom.js
var divs = document.getElementsByTagName('div');
var searchValue=config.toString().split(',');
var div;
var j = searchValue.length;
while(j--){
var i = divs.length;
while (i--) {
div = divs[i];
if(div.innerHTML.indexOf(searchValue[j]) > -1){
div.parentNode.removeChild(div);
}
}
}
popup.js
// Update the relevant fields with the new data
function setDOMInfo(info) {
$("div p:contains(localStorage.getItem('keyWords')).parent('div').hide()");
}
// Once the DOM is ready...
window.addEventListener('DOMContentLoaded', function () {
// ...query for the active tab...
chrome.tabs.query({
active: true,
currentWindow: true
}, function (tabs) {
// ...and send a request for the DOM info...
document.getElementById('myDIV').style.display = 'none';
chrome.tabs.sendMessage(
tabs[0].id,
{from: 'popup', subject: 'DOMInfo'},
// ...also specifying a callback to be called
// from the receiving end (content script)
setDOMInfo);
});
});