Chrome Extension Highlight Feature Not Applying Background Color

68 views
Skip to first unread message

Wuzobia

unread,
Mar 18, 2024, 11:09:15 PM3/18/24
to Chromium Extensions
Hi everyone,
I'm working on a Chrome extension designed to let users highlight text on web pages and save it. Despite setting up the logic to save the selected color and apply it as the background color of the highlighted text, the background color does not change at all, not even to a default color I've attempted to hardcode for testing. 
Here's the popup.js

document.querySelectorAll('.color-option').forEach(element => {
    element.addEventListener('click', function() {
        const selectedColor = this.style.backgroundColor;
        chrome.storage.sync.set({'selectedColor': selectedColor}, function() {
            console.log('Selected highlight color saved:', selectedColor);
        });

        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            chrome.tabs.sendMessage(tabs[0].id, {type: 'colorSelected', color: selectedColor});
        });
    });
});

And this is here is how the highlight is supposed to be applied in the content script

function applyHighlight(selection, color) {
    const range = selection.getRangeAt(0);
    if (!range.collapsed) {
        const span = document.createElement('span');
        span.setAttribute('style', `background-color: rgb(255, 255, 0) !important;`);
        span.textContent = selection.toString();
        range.deleteContents();
        range.insertNode(span);
    }
}

The expected behavior is for the selected text to be highlighted with the user selected color. Nonetheless, no highlighting occurs,the text remains unchanged without any background color applied. The console logs confirms that the color selection from the popup works great.
But the issue persists even when I hardcode the color (e.g., yellow) in the applyHighlight function for testing purposes.
I've checked for errors in the console but haven't found any directly related to applying the highlight.
I'm not sure what I'm missing or doing wrong. Any insights, suggestions, or guidance on how to troubleshoot this issue would be greatly appreciated!
Thank you in advance for your help!

wOxxOm

unread,
Mar 19, 2024, 10:42:30 AM3/19/24
to Chromium Extensions, Wuzobia
There's a lot of things that may be wrong and it could take a lot of guessing, which is ineffective. There's a much better process: use the built-in devtools to debug the content script interactively. Set a breakpoint and see what actually happens in the code and in DOM at the time the code runs, you can also execute the code line by line.
Reply all
Reply to author
Forward
0 new messages