Search code examples
seleniumcapybaracopy-paste

Copy-paste using Capybara?


I would love to do something like this:

div = find '#some-div'
copy_to_clipboard(div)

input = find '#my-input'
paste_from_clipboard(input)

I do not want to simulate this with send_keys and using Ctrl+C and Ctrl+V; I want this to work cross-browser (especially on mobile).

Does this API exist?


Solution

  • There is no Capybara copy/paste API - If all you want to do is copy the visible text into an input then you could do

    div_text = find('#some-div').text()
    find('#my-input').set(div_text)
    

    If that's not correct for what you want, then you could use #execute_script to create a selection range like

    var range = document.createRange();
    range.setStart( <start node>, <start node character offset> );
    range.setEnd( <end node>, <end node character offset> ); 
    
    window.getSelection().removeAllRanges();
    window.getSelection().addRange(range);
    

    then find your target element and set it's value to window.getSelection().toString(). Note that's not really emulating what a user would do, so if you are actually using this for testing an app I would still recommend using the ctrl/cmd-c/v after setting the selection range for browsers that support it since it emulates user behavior better.