I’m working on building a Chrome extension that highlights preselected chemicals on a webpage. However, when I activate the extension, it doesn’t highlight them in blue as I specified in the code. Please advise on what is going on, and why my program does not automatically highlight the chemicals on the webpage.
Content.js file
1: {
English: ["Coconut butter"],
Japanese: ["ココナッツバター"],
Korean: ["코코넛 버터"]
},
2: {
English: ["Coconut oil"],
Japanese: ["ココナッツオイル"],
Korean: ["코코넛 오일"]
},
3: {
English: ["talc"],
Japanese: ["タルク"],
Korean: ["활석"]
},
4: {
English: ["mica"],
Japanese: ["雲母"],
Korean: ["운모"]
},
5: {
English: ["alcohol"],
Japanese: ["アルコール"],
Korean: ["술"]
}
};
let activeHighlights = [];
function highlightText(matches) {
matches.forEach((match) => {
const span = document.createElement("span");
span.className = "highlight";
span.textContent = match.textContent;
match.replaceWith(span);
activeHighlights.push(span);
});
}
chrome.runtime.onMessage.addListener((message) => {
if (message.type === "highlight") {
clearHighlights();
const { levels, languages, customTerm } = message.data;
const regexParts = [];
levels.forEach((level) => {
languages.forEach((lang) => {
if (chemicals[level][lang]) {
regexParts.push(...chemicals[level][lang]);
}
});
});
if (customTerm) regexParts.push(customTerm);
const regex = new RegExp(`\b(${regexParts.join("|")})\b`, "gi");
const matches = Array.from(document.body.querySelectorAll("*:not(script):not(style)"))
.flatMap((node) => Array.from(node.childNodes).filter((child) => child.nodeType === 3))
.filter((node) => regex.test(node.textContent));
highlightText(matches);
}
if (message.type === "clear") {
clearHighlights();
}
});
function clearHighlights() {
activeHighlights.forEach((span) => {
const textNode = document.createTextNode(span.textContent);
span.replaceWith(textNode);
});
activeHighlights = [];
}
Style.css
font-family: Arial, sans-serif;
}
#container {
text-align: center;
padding: 10px;
}
button {
margin: 5px;
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}
button.selected {
background-color: #007bff;
color: white;
}
button.off {
background-color: #ccc;
color: #666;
}
#activateButton {
background-color: #007bff;
color: white;
}
#activateButton.active {
background-color: #28a745;
}
.highlight {
background-color: blue;
color: white;
font-weight: bold;
}