Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set caret position in contenteditable span and then sendKeys?

<span name="workitemContent" contenteditable="">root 0 child 0 zzzz</span>

For instance, how could I use protractor to set my cursor after the word "child" and then send additional text (with sendKeys or similar) into the span at that position?

Afterwards it might look like:

<span name="workitemContent" contenteditable="">root 0 child with red hair 0 zzzz</span>

I've seen other questions that answer how to do this with JavaScript (such as How to set caret(cursor) position in contenteditable element (div)?), but not with protractor.

like image 819
Dave Welling Avatar asked Jan 20 '26 16:01

Dave Welling


1 Answers

You can perform a click on the element with an offset, e.g.:

var elm = element(by.name("workitemContent"));
browser.actions().mouseMove(elm, 5, 0).click().perform();

But, I'm not sure whether you can call it a reliable approach.


Another option would be to follow the solution provided in the question you've linked and execute javascript via browser.executeScript():

var elm = element(by.name("workitemContent"));

function setCursor(arguments) {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(arguments[0].childNodes[2], arguments[1]);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}
browser.executeScript(setCursor, elm.getWebElement(), 5);
like image 118
alecxe Avatar answered Jan 23 '26 04:01

alecxe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!