clipboard copy does not work in jquery ajax success method

后端 未结 6 1539
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:02

    As this is not a user interaction, it will not work.

    The workarounds which we can implement is getting the data from the ajax call as soon as the mouseenter in the area where user wants to copy the data & place the data in some textarea or input box.

    And, on the click event we can copy the data in the clipboard.

    //mouseenter event of a button

    $("#jq-copy-txt").on('mouseenter', function() {
        $.ajax({
          url: 'url',
          method: 'GET'
        }).then(function(data) {
           let copyFrom = document.getElementById("jq-cpy-txt-area"); 
            document.body.appendChild(copyFrom);
            copyFrom .textContent = data.title;
        });
    });
    

    // click event fired by user

    $("#jq-copy-txt").on('click', function() {
    
       var fn = function() {
          let copyFrom = document.getElementsByTagName("textarea")[0];
          copyFrom.select();
          document.execCommand("copy");
        };
        setTimeout(fn, 1000);});
    

提交回复
热议问题