How to access / modify DOM elements in Chrome Extension Manifest V3 content script?

562 Views Asked by At

I have a simple Chrome Extension that logs ids of elements in the console and changes all text element classes to "test".

My manifest.json:

{
  "manifest_version": 3,
  "name": "Access DOM Example",
  "description": "A script accessing and modifying DOM elements",
  "version": "1.0",
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "css": ["test.css"],
    "js": ["test.js"],
    "match_about_blank": false,
    "run_at": "document_end",
    "world": "MAIN"
  }]
}

and content script, test.js:

walk(document.body);

function walk(node) {
    let child, next;

    switch (node.nodeType) {
        case 1:  // Element
        case 9:  // Document
        case 11: // Document fragment
            child = node.firstChild;
            while (child) {
                next = child.nextSibling;
                walk(child);
                child = next;
            }
            break;

        case 3: // Text node
            console.log(node.id);    // shows 'undefined'
            node.className = "test"; // change is never applied, why?
            break;
    }
}

Yet for a simple page:

<html lang="en">
  <body>
    <div id="hello-world">Hello, World!</div>
  </body>
</html>

The script shows 'undefined' in the console and change to class name is not applied.

Is there any way to modify DOM from content script?

0

There are 0 best solutions below