Update: With guidance from "am no I am", I've solved this; working code at the end.
I'm working on my first Chrome extension at the moment, which is intended to perform text replacement on viewed webpages. I've been going all over trying to get my head around DOM manipulation, and I've eventually come up with the following. In theory this should go through the whole DOM table, find text nodes, clone them, replace the text (where applicable), and replace the original node with the clone.
Here's my manifest.json...
{
"name": "My app",
"version": "1.0",
"manifest_version": 2,
"description": "Do thing.",
"permissions": [
"tabs", "http://*/"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["myapp.js"],
"run_at": "document_end"
}
]
}
And the myapp.js;
function myapp() {
var nodes = document.getElementsByTagName("*");
for(var i = 0; i < nodes.length; i++) {
if(nodes[i].type == "text") {
var parent = nodes[i].parentnode;
var newnode = nodes[i].cloneNode(true);
newnode.data.replace("test text","replacement test text");
parent.replaceChild(newnode, nodes[i]);
};
};
};
myapp();
I have the extension imported and activated. Chrome's javascript console has shown errors with it previously, which implies it's running, but has none now, which implies no basic typo-style errors. I assume either I'm wrong about how to alter or swap the text nodes, or have a basic misunderstanding of how to set up the manifest file or the js file, but I've hit a wall trying to figure out which.
Any help would be gratefully received!
Update: Here's the working version.
function myapp() {
var nodes = document.getElementsByTagName("*");
for(var i = 0; i < nodes.length; i++) {
var subNodes = nodes[i].childNodes;
for (var j = 0; j < subNodes.length; j++) {
var node = subNodes[j];
if (node.nodeType === 3) {
if (node.data) {
node.data = node.data.replace(/test text/g,"replacement test text");
}
}
}
}
};
myapp();