Replacing a certain words in a page content with a new element.

101 views
Skip to first unread message

Shiv S

unread,
May 24, 2024, 4:45:25 AMMay 24
to Chromium Extensions
Hello,

I am trying to scan through a page and replace certain words with a new element. Right now, my implementation simply modifies the words using the textContent property. However, I am not sure how to proceed further because I want to replace words with an element and style it so that I can highlight the replaced words with a new color or underline it.

This is my code so far.

Thank you
chrome.storage.local.get("translations", ({ translations }) => {
  if (translations) {
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false);
    let node;

    while (node = walker.nextNode()) {
      const words = node.nodeValue.split(/\b/);
      const newNodeValue = words.map(word => {
        const translation = translations[word.toLowerCase()];
        if (translation) {
            return `*${translation}*`
        }
        return word;
      }).join('');

      node.textContent = newNodeValue
    }
}});

woxxom

unread,
May 24, 2024, 6:53:41 AMMay 24
to Chromium Extensions, Shiv S
The simplest method is to use markjs library. If you want to do it yourself then use node.splitText + createElement as shown in this example: https://stackoverflow.com/a/10730063
Reply all
Reply to author
Forward
0 new messages