简体   繁体   中英

JS copy to clipboard dosn't work

I use fetch to get some text and put this text into textarea. Then I select the text and trying to copy it, but it's not working. Here's the code.

 const copy_text_from_file = (filename) => {
  fetch('/texts/show/?filename=' + filename, {
    credentials: 'include'
  }).then(function(response) {
    return response.json();
  }).then(function(json) {
    const textarea = document.getElementById('clipboard');
    textarea.focus();
    textarea.innerHTML = json.content;
    textarea.select();
    console.log( document.execCommand('copy') ); // writes false to console
  });
};

Text is inserted and textarea is selected and is in focus, but nothing is copied. When I run document.execCommand('copy') from browser's console it works. I tried adding timeouts but it doesn't help. I tried adding button with click event listener and trigger button with click() to copy selected text, but it doen't help either.

PS Textarea is visible.

document.execCommand('copy') only works when trusted user action, such as a click event.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM