I am looking for a way to add a frame/border (like Evernote Web Clipper: below image) around my selected text into my Chrome extension.
To do that, I thought capture the HTML code of the selection and add a frame/border around the current selected text. But I don't see how can I do that...
Here is my code:
Manifest.json:
{
"name": "Selected Text",
"version": "0.1",
"description": "Selected Text",
"manifest_version": 2,
"browser_action": {
"default_title": "Selected Text",
"default_icon": "online.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["popup.js"]
}
]
}
popup.js:
chrome.tabs.executeScript( {
code: "window.getSelection().toString();"
}, function(selection) {
console.log(selection[0]);
if(selection[0].length > 0){
document.getElementById("text").value = selection[0];
}
});
popup.html:
<!DOCTYPE html>
<html>
<head>
<script src="popup.js"></script>
<style>
body { width: 300px; }
textarea { width: 250px; height: 100px;}
</style>
</head>
<body>
<textarea id="text"> </textarea>
</body>
</html>
You can do it with mouseup
event like this:
// Add event listener for mouseup (there is no event for selection)
document.addEventListener('mouseup', highlightSelectedBlock, false)
function highlightSelectedBlock () {
// TODO Filter only selections
// Get Node where selection starts
let elementWhereSelectionStart = window.getSelection().anchorNode
// TODO Get Node where selection ends with Selection.focusNode()
// TODO Get Nodes in between start and end of selection
// I've hardcoded finding closest block element for a simplicity
let closestBlockElement = elementWhereSelectionStart.parentNode
// Add non disturbing border to selected elements
// For simplicity I've adding outline only for the start element
closestBlockElement.style.outline = '1px solid blue'
// TODO Clear outline on some event: saving selection, ending selection etc
setTimeout(() => { closestBlockElement.style.outline = 'none' }, 2000)
}
<p>First line
<p>Second line
<p>Third line
But for real life it should be more complex, think of:
Maybe it can be a good idea to constantly poll DOM for a selection object with window.requestAnimationFrame() instead of adding event listener to mouseup
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With