I want to modify the DOM, which api should i use ?
I basically want to take a name of a text and bold it. example
original:
<p>Hello World</p>
modified:
<p>Hello <b>World</b></p>
8 Replies
Probably just need a main world content script to do the work.
I’m not sure you need a main world content script for that? You can add classes to arbitrary elements and whatnot from CSUI which I’m pretty sure isn’t main world
@Tsuni has reached level 1. GG!
Maybe not a main world, but I've found that it depends on what part of the DOM or browser API you want to access. For example I don't think you can access global JS variables outside of MAIN world or even LocalStorage.
So for example say you wanted to update the text of a button on the google home page. It currently says "Google Search" and you want it to be something else. In this case I would create a contents script like this.
I haven't actually tested this but it should work.
Now in your case you'll probably need to use a mutation observer to detect changes. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
But that all depends on if your needs. If its a SPA you'll prob need the observer, if its just a webpage that loads every page you visit then this script should work.
MDN Web Docs
MutationObserver - Web APIs | MDN
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.
This JS works on this HTML, too.
My understanding is that the "main" world is the context of the page's JS and its globals. It would be bad to have every extension running in that same namespace, because if they were to, for example, reassign a global it would break other extensions that relied on that global. I don't think it has much, if any, effect on what you can do with the DOM, since that's not JS.
im not following your answer. i just need help to get the base code to modify DOM and add the bold tag
That is code that will modify the DOM. You create a content script that runs on the specified domain (
matches
) and once the document has been parsed it'll execute the code.