I am working on a Chrome extension that will extract a simple text url from a selection, but the selection will always be part of the URL, so I need to scan left and right. I need to extract 500 characters around the selection from innerText, since I do not want to parse the html elements, nor do I want to reassemble the textContent.
Here is what I have so far, it works very well, but I feel that there is a better way that does not change the document object and then restores it back to its original state ...
Instance
contains the extracted text, line breaks, etc., which are evaluated by the browser. This, by the way, will be Chrome only because I do not need cross-compatibility at all. Now I can parse the selection - from the middle to the edges to find the URL, note that starting the parsing from the middle is important, so I didnโt just extract the innerText from the parentNode of my getSelection () without knowing the offset ...
Is there a better way to do this? maybe copying the whole document into DOMParser, but how can I apply getSelection from the original document to it?
------ UPDATE ------
I simplified the code above (forgot to mention that I work with mouse clicks to detect a click event, after double-clicking to select text) and now it finds caretOffset in document.body.innerText, but it still changes the document and then restores it, so still thinking of a better way to do it. I am wondering if insertNode and deleteContents are bad in some way?
var randId = Math.floor(Math.random()*(90000000)+10000000); var range = document.caretRangeFromPoint(event.clientX, event.clientY); range.insertNode(document.createTextNode(randId)); var everything = document.body.innerText; var offset = everything.indexOf(randId); range.deleteContents(); var everything = document.body.innerText; var extract = everything.substring(offset-250, offset+250); document.getSelection().anchorNode.parentNode.normalize();
Any thoughts?
source share