I am trying to rebuild a Range() object in a client browser using websites.
https://jsfiddle.net/k36goyec/
First I get a Range object in my browser and Node where the range starts:
var range = window.getSelection().getRangeAt(0); var node = range.startContainer
I pass three parameters through websockets to the range-building function in the client browser.
var text = node.parentNode.textContent; var startOffset = range.startOffset var endOffset = range.endOffset
this data is passed to my buildRange function:
buildRange: function(text, startOffset, endOffset){ var node = this.getNodeByText(text);
As you can see below, I get a node in the client browser, iterating over all the elements on the page and comparing its contents with the text:
getNodeByText: function(text){ var all = document.getElementsByTagName("*"); for (var i = 0; i < all.length; i++) { if (all[i].textContent === text) { return all[i]; } } },
I use setStart () and setEnd () to set the range of my selection to node.
Problems!
range.startOffset / endOffset indicates the following:
If startNode is a node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the beginning of startNode. For other types of nodes, startOffset is the number of child nodes between the start of startNode.
When I select a range of text, I get the following error:
IndexSizeError: Index or size is negative or greater than the allowed amount
This is because I pass the offset as 0, 10 (10 characters selected), but the node is a node element, not the text node.
I just can't reliably get the node text, I can only get the node element itself ...
IN:
How can I reliably rebuild a range using node and offsets?