This is pretty easy to do actually.
You can get the selection start and selection end from any textfield.
Take a look at this.
It would work like the following:
document.onselectionchange = function() {
let inp = document.querySelector("input");
document.querySelector("p").innerText = "Start: "+inp.selectionStart+"\nEnd: "+inp.selectionEnd+"\n\nSelected: "+inp.value.substring(inp.selectionStart, inp.selectionEnd);
}
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<p></p>
<input>
</body>
</html>
If you want to get the position, that doesn't work with inputs for some reason, but here's the code for that too. It grabs the boundingRect from the selection range.
document.onselectionchange = function() {
let inp = document.querySelector("div");
let sel = document.getSelection();
let bound = sel.getRangeAt(0).getBoundingClientRect();
document.querySelector("p").innerText = "Selected: "+inp.innerText.substring(sel.selectionStart, sel.selectionEnd)+"\n\nX: "+bound.left+"\nY: "+bound.top+"\n\nWidth: "+bound.width+"\nHeight: "+bound.height;
}
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<p></p>
<div style="border: 1px solid black" contenteditable="true">
</body>
</html>