Cucumber + Capybara + Selenium: selecting text

让人想犯罪 __ 提交于 2019-12-07 08:12:30

问题


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?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/4473887/cucumber-capybara-selenium-selecting-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!