execCommand('copy') does not work in Ajax / XHR callback?

后端 未结 2 1451
鱼传尺愫
鱼传尺愫 2020-12-10 15:45

(Tested using Chrome 44)

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

Actual be

2条回答
  •  孤城傲影
    2020-12-10 16:07

    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();
    });
    
    
    
    
    
    
      

提交回复
热议问题