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();
There may also be issues with the iteration since you’re modifying the DOM, and
nodesis a “live” NodeList that will update with DOM changes.Not sure if this is an issue since you seem to be doing a swap at the same index, but I’m not sure. You could try converting the NodeList to an Array, or try iterating in reverse.
But since you’re only dealing with text nodes, it would seem that you don’t need the
.replaceChildat all. You could just update the.dataof the text node directly.One more thing is that you’re checking the
.typeproperty, when it should probalby be the.nodeTypeproperty…Or the
nodeName…Oh, one more thing. You can’t get text nodes using
getElementsByTagName('*'), because it only fetches elements.If you decide to do it that way, you’ll need to add code to deal with the child text nodes of the elements.