1

I've got a script that deals with pasted text in a text area. I would like to write some tests for it. The first step would be to copy some text in the clipboard so after reading a lot about the topic I ended up with something like this:

  1. Add a text Area to the DOM with the text you want to copy.
  2. Add a button to the DOM that runs document.execCommant("copy") on click.
  3. Remove the text area & the button from the DOM.

Please take into account before marking this question as a duplicate, that all the other solutions I've seen involve the user performing the click action. I am asking about how to do this strictly programmatically.

document.execCommant("copy") does not work if it's not triggered by any user action due to security reasons. In my case, the tests are clicking on the button, but document.execCommant("copy") simply won't work.

Is there any way of doing this without using any new libraries? (jQuery is fine).

I am interested in a solution that works on Chrome/Firefox.

Here you can see a fiddle with the step I mentioned above: https://jsfiddle.net/7b40ma0q/

jobmo
  • 835
  • 1
  • 9
  • 19
  • look here please http://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript – TypedSource Apr 07 '17 at 15:55
  • How about using clipboard events? https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent. You can also look here to ensure compatibility with the target browser: http://caniuse.com/clipboard – jrook Apr 07 '17 at 15:57
  • 1
    You can't without any user interaction. Regardless, honest question: why would you test this? – Sergiu Paraschiv Apr 07 '17 at 16:08
  • @SergiuParaschiv, cause I do some actions based on the content of the text I paste in the text area, so I want to make sure that the entire workflow works as expected. – jobmo Apr 10 '17 at 07:45
  • @jrook following the link http://caniuse.com/#feat=clipboard I've noticed the EventConstructor is not supported on Chrome v57, so we cannot copy anything to the clipboard – jobmo Apr 10 '17 at 07:48
  • @jobmo, the link in your comment does not work. caniuse website and MDN both show support for Chrome (including v57). In any case it is still an experimental feature and might not work as expected. – jrook Apr 10 '17 at 08:09

0 Answers0