I need to create a Chrome Extension which people can use to look up words. And I have found that I use double-click method like when I want to find meaning of a word I just double click and then the notification will appear. (The image below is my Chrome Extension.)
To get the text selected you could use this function, then remove the dots, and other characters you are not interested in and split the selected text by spaces to get the last word. (also you don't need the cursor coordinates for it, so you could remove this piece. of the code)
let hasSelection = false;
function showCoordsForMouseUp(event) {
const selection = window.getSelection().toString()
hasSelection = selection.length;
if (hasSelection) {
const x = event.clientX;
const y = event.clientY;
const coords = `X coords: ${x} , Y coords: ${y}`;
console.log(`${coords} - ${selection}`)
} else {
console.log('No text selected')
}
}
document.onmouseup = showCoordsForMouseUp;
Thanks for your contribution, I have found the solution with onMouseUp Event.
document.onmouseup = function F(e) {
x = e.pageX;
y = e.pageY;
if (window.getSelection().toString() != "") {
console.log("X: " + x + "Y: " + y);
}
}
<p>
Flower, flowers.
</p>