Search code examples
javascripttestingseleniumprotractorend-to-end

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.


Solution

  • 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);