Cucumbers + Capybara + Selenium: text selection

I am making changes to a text editor, and I need to be able to select text to manipulate it using JavaScript. How to choose text with cucumbers, cappibara and selenium?

+4
source share
2 answers

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

Can you set and / or change the text selection for users in JavaScript?

I managed to modify their script to work in the getEval call from the Selenium IDE (if you use Selenium in a different way, you may need to change it). I also removed the non-Firefox code:

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 identifier of the element containing the text, and 10 and 20 are the indices of the characters to start and stop.

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

If text within a single element is not enough for you, the JavaScript range documentation should provide you with the additional information you need.

+3
source

Binding the approach proposed by Josh to the Capybara helper function (and adding optional position arguments for partial selections in 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) 
0
source

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


All Articles