9

(Tested using Chrome 44)

Desired behaviour: Make XHR request, put result in text area, select text, and copy to clipboard.

Actual behaviour: On successful XHR request, puts the result in text area and selects it, but fails to copy result to clipboard. But if I initiate the copy outside of the XHR callback, it works.

Example html page:

var selectAndCopy = function() {
  // Select text
  var cutTextarea = document.querySelector('#textarea');
  cutTextarea.select();
  // Execute copy
  var successful = document.execCommand('copy');
  var msg = successful ? 'successful' : 'unsuccessful';
  console.log('Cutting text command was ' + msg);
};

var fetchCopyButton = document.querySelector('#fetch_copy');
fetchCopyButton.addEventListener('click', function(event) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', 'http://httpbin.org/ip');
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        // Set text
        var textarea = document.querySelector('#textarea');
        textarea.value = xhr.responseText;

        selectAndCopy();
      }
    }
  };
  xhr.send();
});

var copyButton = document.querySelector('#copy');
copyButton.addEventListener('click', function(event) {
  selectAndCopy();
});
<html>

<head>
</head>

<body>
  <p>
    <textarea id="textarea">Hello, I'm some text!</textarea>
  </p>
  <p>
    <button id="fetch_copy">Fetch Data and Copy Textarea</button>
    <button id="copy">Copy Textarea</button>
  </p>
</body>

</html>

If you press the "Fetch Data and Copy Textarea" button the data is successfully fetched but not copied. If you press the "Copy Textarea" button the text is copied as expected. I've tried many combinations of request/copy to try and get it to work but to no avail (including programmatically pressing the copy button after fetching data). Does anyone know what's going on here? Is this a security feature or something?

I don't want the user to have to press two buttons to fetch and copy if possible.

Kukeltje
  • 11,924
  • 4
  • 19
  • 44
aeoliant
  • 357
  • 2
  • 9
  • So how did you solve it in the end? Could you update the question? – ChrisGeo Jan 31 '17 at 19:14
  • @ChrisGeo I ended up just selecting the text (but not copying it). I realized users probably wouldn't be happy if I overwrote something in their copy buffer. Trevor's answer below looks like it will work (if you are ok with synchronous XHR) – aeoliant Mar 07 '17 at 21:36
  • This problem is solved in my ans :) here: http://stackoverflow.com/questions/43380921/not-able-to-copy-a-link-directly-when-i-am-using-ajax/43381458#43381458 – Nishanth Matha Apr 13 '17 at 05:03
  • Perhaps, you could do something which I mentioned here: [SOLVED: document execCommand copy not working with AJAX](http://stackoverflow.com/questions/43380921/not-able-to-copy-a-link-directly-when-i-am-using-ajax/43381458#43381458) – Nishanth Matha Apr 13 '17 at 07:54
  • there's a hack here using `setTimeout` if the action was initiated from a `trusted` event: https://stackoverflow.com/a/40826549/3649573 – AlbinoDrought Apr 05 '19 at 22:53

2 Answers2

17

You can only trigger a copy to the system clipboard in direct response to a trusted user action, such as a click event.

Spec: http://www.w3.org/TR/clipboard-apis/#integration-with-rich-text-editing-apis

Tim Down
  • 292,637
  • 67
  • 429
  • 506
  • I have sloved this problem here :) http://stackoverflow.com/questions/43380921/not-able-to-copy-a-link-directly-when-i-am-using-ajax/43381458#43381458 – Nishanth Matha Apr 13 '17 at 05:04
8

DISCLAIMER: Synchronous XMLHttpRequests are not recommended on the main thread. Please read this and make sure you know what you're doing before using this solution. THIS IS NOT RECOMMENDED FOR PRODUCTION USE.

If you make the XMLHttpRequest synchronous, this will work. You just have to add false as the third parameter to xhr.open(...):

var selectAndCopy = function() {
  // Select text
  var cutTextarea = document.querySelector('#textarea');
  cutTextarea.select();
  // Execute copy
  var successful = document.execCommand('copy');
  var msg = successful ? 'successful' : 'unsuccessful';
  console.log('Cutting text command was ' + msg);
};

var fetchCopyButton = document.querySelector('#fetch_copy');
fetchCopyButton.addEventListener('click', function(event) {
  var xhr = new XMLHttpRequest();
  xhr.open('get', 'http://httpbin.org/ip', false);
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        // Set text
        var textarea = document.querySelector('#textarea');
        textarea.value = xhr.responseText;

        selectAndCopy();
      }
    }
  };
  xhr.send();
});

var copyButton = document.querySelector('#copy');
copyButton.addEventListener('click', function(event) {
  selectAndCopy();
});
<html>

<head>
</head>

<body>
  <p>
    <textarea id="textarea">Hello, I'm some text!</textarea>
  </p>
  <p>
    <button id="fetch_copy">Fetch Data and Copy Textarea</button>
    <button id="copy">Copy Textarea</button>
  </p>
</body>

</html>
Trevor
  • 11,966
  • 11
  • 74
  • 94
  • 3
    Synchronous XHR is generally a bad idea but it's difficult to see a way to do this in one step without it. Also, you'll get warnings about synchronous XHR requests in Chrome's console. – Tim Down Jan 03 '17 at 10:28
  • Yes, it's bad idea but I have seen this that making Synchronous XHR works! When I had it as async, Firefox complained "document.execcommand('copy') was denied because it was not called from inside a short running user-generated event handler", however, no problem when the Ajax call was made sync!!! What could be the reason? – curious.netter Oct 30 '19 at 09:35