document execCommand copy not working with AJAX

后端 未结 2 1951
[愿得一人]
[愿得一人] 2020-12-04 02:21

I can\'t copy the generated link directly (without ctrl+C) I am usign document.execCommand(\'copy\') but it seems it has no effect. If code has no AJAX

2条回答
  •  一整个雨季
    2020-12-04 02:46

    I had the same problem. I solved it rather primitively: inside the handler of a click event, you can run an interval that will check the variable where ajax will insert the value after the server responds. After the answer is received, we stop the interval and start the work with the clipboard. No problem, because the user himself starts the interval after the click, without any callbacks.

    Simple jQuery example:

    var ajaxResponse;
    
    function copyText(copiedText){
      $('').appendTo('body');
    
      if ( navigator.userAgent.match(/ipad|iphone/i) ) {
        var range = document.createRange(),
            textArea = $('.copied-text')[0];
        range.selectNodeContents(textArea);
        var selection = window.getSelection();
        selection.removeAllRanges();
        selection.addRange(range);
        textArea.setSelectionRange(0, 999999);
      } else {
        $('.copied-text').select();
      }
    
      document.execCommand('copy');
      $('.copied-text').remove();
    };
    
    function myAjaxFunc(){
      $.ajax({
        type: 'POST',
        url: yourUrl,
        data: yourData,
        success: function(data){
          ajaxResponse = data;
        }
      });
    };
    
    $('.your-button').on('click', function(){
      myAjaxFunc();
      var ajaxCheckTimer = setInterval(function(){
        if ( ajaxResponse ) {
          copyText(ajaxResponse);
          clearInterval(ajaxCheckTimer);
        };
      }, 100);
    });
    

    In this example, when clicking on a button, we send some data to the server and start the interval with checking the value of the ajaxResponse variable.

    After the response from the server is received, the response of the server is written to this variable, after which the condition in the interval becomes true and the text copy function is called, and the server response variable is specified as the parameter: copyText(ajaxResponse);. The interval stops.

    The copyText function creates an textarea on the page with the value of the ajaxResponse variable, copies this value from the field to the clipboard, and deletes the field from the page.


    UPDATE 01.07.19

    For correct copying to the clipboard on iOS, add the attribute contenteditable with the valuetrue to the text field:

    $('').appendTo('body');
    

提交回复
热议问题