Highlighting the text on a page (or doing anything on the page) via a Chrome Extension must be done through a Content Script. However your popup has to talk to the Content Script to tell it to highlight the page when the button is click in the popup. This is called Message Passing.
Your popup.js
should look something like this:
document.getElementById('highlight').addEventListener('click', sendHighlightMessage, false);
function sendHighlightMessage() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {highlight: true}, function(response) {
console.log(response);
});
});
}
content_script.js
is where the DOM manipulation actually happens. It should listen for the message from your popup and appropriately highlight the page. It should contain the following:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.highlight === true) {
highlightText(document.body);
sendResponse({messageStatus: "received"});
}
});
Read through the Chrome Extension documentation on content scripts and message passing (linked above) for a more complete explanation of what's going on here.
Actually highlighting text on the page as in selecting it (like clicking and dragging over text to copy and paste) can't be done programmatically outside a textarea or input field. However, you can use styling to change the background color of the text. In order to highlight just the text, you need to wrap each text node in a span, with the highlight style. This is a lot of DOM manipulation and will completely mutilate the original page. You should consider whether this is really necessary and useful for your extension. That said, it will look something like this:
function highlightText(element) {
var nodes = element.childNodes;
for (var i = 0, l = nodes.length; i < l; i++) {
if (nodes[i].nodeType === 3) // Node Type 3 is a text node
var text = nodes[i].innerHTML;
nodes[i].innerHTML = "<span style='background-color:#FFEA0'>" + text + "</span>";
}
else if (nodes[i].childNodes.length > 0) {
highlightText(nodes[i]); // Not a text node or leaf, so check it's children
}
}
}