Cucumber + Capybara + Selenium: selecting text

2019-05-07 18:21发布

I'm making changes to a text editor, and I need to be able to select text to manipulate it with JavaScript. How do I select text with Cucumber, Capybara and Selenium?

2条回答
爷、活的狠高调
2楼-- · 2019-05-07 19:10

Tying the approach suggested by Josh into a Capybara helper function (and adding optional position arguments for partial selections within the start/end elements):

module TextSelection
  def select_text(startEl, endEl, startPos = 0, endPos = 0)
    js = <<-JS
      var sel = window.getSelection();
      var range = window.document.createRange();
      range.setStart(arguments[0],#{startPos});
      range.setEnd(arguments[1],#{endPos});
      sel.removeAllRanges();
      sel.addRange(range);
    JS

    page.execute_script(js, startEl.native, endEl.native)
  end
end

World(TextSelection)

Then, in your test:

start_el = first('#first')
end_el = first('#last')
select_text(start_el, end_el)
查看更多
聊天终结者
3楼-- · 2019-05-07 19:20

I found another stackoverflow question that talks about how to select text using JavaScript.

Can you set and/or change the user’s text selection in JavaScript?

I was able to modify their script to be able to work within a getEval call from Selenium IDE (if you're using Selenium in a different way, you may need to modify it). I also stripped out the code not pertinent to Firefox:

function selectElementContents(el,start,end) {
    var sel = window.getSelection();
    var range = window.document.createRange();
    range.setStart(el,start);
    range.setEnd(el,end);
    sel.removeAllRanges();
    sel.addRange(range);
}
selectElementContents(window.document.getElementById("container").firstChild,10,20)

This allows you to select a range of text within a single element. "Container" is the ID of the element containing the text, and 10 and 20 are the indexes of characters to start and stop at.

Just condense this down to one line, add it to a Selenium getEval statement, and it should select the text for you.

If text within a single element isn't flexible enough for you, documentation on JavaScript ranges should provide you the extra detail you need.

查看更多
登录 后发表回答