简体   繁体   中英

Chrome extension highlight text on rick click

I have a chrome extension where I want to be able to highlight text when I right click it. Right now, I'm able to get my button to appear on the right click options bar (via contextMenu's), but I can't for the life of me figure out how to change the bg color of the text. Any ideas how?

//This block is not working - I want to change selected text bg color
function radioOnClick(info, tab) {
    elements = document.getElementsByClassName("author");
    for (var i = 0; i < elements.length; i++) {
        if (elements[i].innerText == info.selectionText) {
            elements[i].style.backgroundColor="red";    
        } else {
            elements[i].style.backgroundColor="";
        }
    }
}

//This block works properly in showing the options
var radio1 = chrome.contextMenus.create({"title": "Sending", "contexts":["selection"], "type": "radio", "onclick":radioOnClick});
var radio2 = chrome.contextMenus.create({"title": "Remove them", "contexts":["selection"], "type": "radio", "onclick":radioOnClick});

Let's assume that there is the text "qweSELasd" and SEL is the selected part which you want to be highlighted with a different background. You need to split the text node into three parts ("qwe", "SEL" and "asd") by calling the splitText function twice and change the background for the second ("SEL") node. But you can't change the background for text nodes, only for elements, so the simplified code:

 let s = document.getElementsByTagName('div')[0] let second = s.firstChild.splitText(3) second.splitText(3) console.log(s, second) let spn = document.createElement('span') spn.appendChild(second.cloneNode()) second.parentNode.replaceChild(spn, second) spn.style.background = 'red' 
 <div>qweSELasd</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM