Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. (function(){
  2. var copyToClipboard = str => {
  3. var el = document.createElement('textarea'); // Create a <textarea> element
  4. el.value = str; // Set its value to the string that you want copied
  5. el.setAttribute('readonly', ''); // Make it readonly to be tamper-proof
  6. el.style.position = 'absolute';
  7. el.style.left = '-9999px'; // Move outside the screen to make it invisible
  8. document.body.appendChild(el); // Append the <textarea> element to the HTML document
  9. var selected =
  10. document.getSelection().rangeCount > 0 // Check if there is any content selected previously
  11. ? document.getSelection().getRangeAt(0) // Store selection if found
  12. : false; // Mark as false to know no selection existed before
  13. el.select(); // Select the <textarea> content
  14. document.execCommand('copy'); // Copy - only works as a result of a user action (e.g. click events)
  15. document.body.removeChild(el); // Remove the <textarea> element
  16. if (selected) { // If a selection existed before copying
  17. document.getSelection().removeAllRanges(); // Unselect everything on the HTML document
  18. document.getSelection().addRange(selected); // Restore the original selection
  19. }
  20. };
  21.  
  22.  
  23. copyToClipboard("foo\tbar")
  24.  
  25. console.log("copied")
  26. }())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement