2

I am trying to capture the copy event and update the clipboard with some information. Below is what I am trying, it works fine except when the user tries to copy using the right click -> copy option. Not only does this not work but it also doesn't allow the basic copy action.

<h1 onCopy="dosomething()">
blah1 lorem ispum eng auf
</h1>

<script type="text/javascript">
function dosomething() {

    var selection = window.getSelection().toString();
    var formattedSelection = selection.trim() + "-random";
    var textarea = document.createElement('textarea');
    console.log("f=", formattedSelection);
    textarea.textContent = formattedSelection;
    textarea.style.position = 'fixed';  // Prevent scrolling to bottom of page in MS Edge.
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');            
    document.body.removeChild(textarea);

};
</script>

Can someone help me find what I may be doing wrong here? Prepared a jsfiddle here for easier debugging - https://jsfiddle.net/a74x41rk/

EDIT -

I got this to work with a setTimeout, still not sure why though.

setTimeout(function(){      
        document.execCommand('copy');
        document.body.removeChild(textarea);
      });     

updated fiddle - https://jsfiddle.net/a74x41rk/1/

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281

0 Answers0