I am working on a Chrome extension that highlights text in the same was as CTRL+F and I found this code that highlights text.
However, upon trying to implement it, I've been running into some trouble where everything run perfectly except the document.execCommand("HiliteColor") and document.execCommand("BackColor") functions.
I've read from this post that execCommand does not work in content_script, so it must be sent to the background page.
However, background pages have been replaced by service_workers, which when trying to use it, does not recognize the window variable.
Is there a way to implement the following functions without downgrading to manifest_version 2 and refactoring most of the code.
Code
manifest.json:
{
"manifest_version": 3,
"name": "ext",
"version": "1.0",
"description": "Extension",
"icons": {
"48": "icon.png"
},
"permissions": [
"tabs",
"storage",
"activeTab"
],
"host_permissions": [
"https://api.com/*"
],
"action": {
"default_popup": "popup.html",
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"scripts/Highlight.js"
]
}
]
}
scripts/Highlight.js
function highlightSelection(color) {
var sel = window.getSelection();
var range = sel.getRangeAt(0);
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
console.log("Design mode on");
if (!document.execCommand("HiliteColor", false, color)) {
document.execCommand("BackColor", false, color);
}
console.log("Design mode off");
document.designMode = "off";
}
chrome.runtime.onMessage.addListener((request) => {
console.log(request);
for (let index = 0; index < request.textArray.length; index++) {
const element = request.textArray[index];
console.log(element)
window.find(element.text);
highlightSelection(element.color);
}
});
The Listener receives a message with the following code:
function sendHighlight(color, errors) {
chrome.tabs.query({ active: true, currentWindow: true}, function(activeTabs) {
chrome.tabs.sendMessage(activeTabs[0].id, { errors, color }, (response) => {
console.log(response);
});
});
}
document.getElementById("button").addEventListener("click", () => sendHighlight("blue", ["Hello", "apple", "arraycontent"]));
What I tried
So far, I tried to comment the window.find() and just hightlight the selected text on the window, however the code seems to completely ignore the execCommand or at least not work as intended.
I also tried to modify the manifest as such:
"background": {
"service_worker": "scripts/Highlight.js"
}
But it does not seem to recognize global var such as window and document.