Insert text at cursor position without clicking on blank lines

I use this native javascript method in GWT to insert text at the cursor position of a RichTextArea. It works sometimes, but it often gives me this error message: "refNode.insertData is not a function. It seems to happen when the cursor is on an empty line.

public native void insertText(String text, int pos) /*-{ var elem = this.@com.google.gwt.user.client.ui.UIObject ::getElement()(); var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer; refNode.insertData(pos, text); }-*/; 

So I need to debug this javascript and don't know where to start. I know very little about javascript and got this method, which I use from the question stack. I get the cursor position from another native method that I copied from this question .

I read that this error is due to the fact that refNode is not the correct type of object. I figured that someone knows what type of object it really is, and can help me deal with this situation.

+2
source share
2 answers

So I have this job, I think. I changed Matthew's answer a bit, and it seems to work in all my tests. When refNode is equal to the type of the element, I assume that the value of pos was always the index of the child element of the node that I needed to insert into earlier.

 public native void insertText(String text, int pos) /*-{ var elem = this.@com.google.gwt.user.client.ui.UIObject ::getElement()(); var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer; if (refNode.nodeType == 1) { var newTextNode = document.createTextNode(text); refNode.insertBefore(newTextNode, refNode.childNodes[pos]); } else { refNode.insertData(pos, text); } }-*/; 
0
source

I assume that the refNode problem is not the correct type. One possible solution is to check the type of refNode, and if it is not of type TEXT_NODE, create the text node and add it to refData. The code will look something like this:

 public native void insertText(String text, int pos) /*-{ var elem = this.@com.google.gwt.user.client.ui.UIObject ::getElement()(); var refNode = elem.contentWindow.getSelection().getRangeAt(0).endContainer; if(refNode.nodeType == 3){ var newTxtNode = document.createTextNode(text); refNode.appendChild(newTxtNode); } else { refNode.insertData(pos, text); } }-*/; 

This type of nodeType can be found here .

+2
source

Source: https://habr.com/ru/post/1483391/


All Articles