clipboard copy does not work in jquery ajax success method

后端 未结 6 1577
Happy的楠姐
Happy的楠姐 2021-01-14 03:38

I want to copy a card number into the clipboard so that I can paste it in Notepad. The code which I got from the internet works very well if tried in the developer toolbar o

6条回答
  •  轮回少年
    2021-01-14 04:18

    Updated:

    User interaction is mandatory to execute document.execCommand. So in your case it is not possible to copy the text from AJAX Response. It is the security measure that browsers agreed upon.

    Refer W3C API

    Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.


    A workaround with user interaction

    Steps added:

    • Place a text box far away from webpage using relative position.
    • Add a button in a disabled state. Once data is available re-enable the button.
    • On button click you will be able to perform document.execCommand since you are directly interacting with browser (Hence no security issue as mentioned in API)

    $(document).ready(function() {
      $.ajax({
        url: 'https://jsonplaceholder.typicode.com' + '/posts/1',
        method: 'GET' 
      }).then(function(data) {
        console.log(data);
        $('#toBeCopied').val(data.title);
        $("#copyIt").attr('disabled', null);
      });
    
      
    });
    function copyToClipboard(){
        var $temp = $("");
        $("body").append($temp);
        $temp.val($("#toBeCopied").val()).select();
        var result = false;
        try {
            result = document.execCommand("copy");
        } catch (err) {
            console.log("Copy error: " + err);
        }
        $temp.remove();
      }
    
    
    Below button will be enabled once the data is available from AJAX
    

提交回复
热议问题