I want to have a Chrome Extension that will replace text on a page. I've got all the code working on the Javascript side of things, and it runs perfectly when a page loads, the problem is I only want it to replace the text on the page when you click a button on the toolbar.
I setup a button on the toolbar but the replacement Javascript still just runs when the page loads, rather than when you click the button. Additionally at the moment when you click the toolbar button, despite it not doing anything, it still shows a flash of a popup window. All I want it to do is run the text replacement code when you click the toolbar button, without showing a popup.html box.
The code currently is as follows,
Manifest.json
{
"name": "Browser Action",
"version": "0.0.1",
"manifest_version": 2,
"description": "Show how options page works",
// Needed to retrieve options from content script
"background": "background.html",
// This is how you load Browser Action. Nearly equal to Page one.
"browser_action": {
"default_icon": "icon.png",
"popup": "popup.html"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js" : ["popup.js"]
}
]
}
popup.js
function htmlreplace(a, b, element) {
if (!element) element = document.body;
var nodes = element.childNodes;
for (var n=0; n<nodes.length; n++) {
if (nodes[n].nodeType == Node.TEXT_NODE) {
var r = new RegExp(a, 'gi');
nodes[n].textContent = nodes[n].textContent.replace(r, b);
} else {
htmlreplace(a, b, nodes[n]);
}
}
}
htmlreplace('a', 'IT WORKS!!!');
popup.html - Blank
background.html
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "popup.js"});
});