Change DOM Content With Chrome Extension
You need to use this query to send data to DOM from the current tab being viewed.
chrome.tabs.executeScript(null, {
code: 'var config = ' + JSON.stringify(getKeywords)
}, function() {
chrome.tabs.executeScript(null, {file: 'custom.js'});
});
and in the custom.js
file you can write you function that you want to apply on the DOM element. like if you want to hide something than you need that query in custom.js
. So if you wanted to use that example you would need to modify it according to your requirements.
var all = document.getElementsByTagName("div");
var searchValue=config.toString().split(',');
alert('Example:' + searchValue[0]);
for(j=0; j < searchValue.length; j++) {
for(i=0; i < all.length; i++) {
if(all[i].innerHTML.indexOf(searchValue[j]) > -1){
all[i].innerHTML = ""
}
}
}
You should send command from background.js or popup.js, receiving that and change the dom in content.js. The following code demonstrate a simple scenario: Click the browserAction and append a div to the current page. You can use the same logic to show/hide any elements.
manifest.json
{
"name": "Test",
"version": "1.0",
"permissions": [
"tabs"
],
"description": "Test",
"background": {
"persistent": false,
"scripts": [
"background.js"
]
},
"content_scripts": [
{
"matches": [
"*://*/*"
],
"js": [
"content.js"
],
"run_at": "document_end",
"all_frames": true
}
],
"browser_action": {
"title": "Test"
},
"manifest_version": 2
}
background.js
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {command: "append"}, function(response) {
console.log(response.result);
});
});
});
content.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request.command);
var div = document.createElement('div');
var label = document.createElement('span');
label.textContent = "Hello, world";
div.appendChild(label);
document.body.appendChild(div);
sendResponse({result: "success"});
});