Advertisement
Kawiesh

Vanilla JS onclick copy w/ fallback

Jan 18th, 2021 (edited)
926
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 1) Clipboard API: navigator.clipboard.writeText(text)
  2. Text can be copied to the clipboard directly from a variable.
  3. Only supported on pages served over HTTPS
  4.  
  5. 2) document.execCommand('copy') 👎
  6. Deprecated, but still supported by many browsers
  7.  
  8. 3) Overwrite what is being copied to the clipboard.
  9. element.oncopy=(e)=>{
  10. e.clipboardData.setData('text/plain', text);
  11. e.preventDefault();
  12. };
  13.  
  14.  
  15. //Clipboard API with fallback to document.execCommand("copy");
  16.  
  17. function copyText(text) {
  18. let a;
  19. let textarea= text instanceof HTMLTextAreaElement;
  20. let input= text instanceof HTMLInputElement && text.type == "text";
  21.  
  22. if(textarea||input){ a= text; }
  23. else{
  24. a= document.createElement("textarea");
  25. a.style.cssText= "opacity:0; pointer-events: none;"
  26. document.body.append(a);
  27. a.value= text;
  28. }
  29.  
  30. try{
  31. navigator.clipboard.writeText(a.value);
  32. }
  33. catch(x){
  34. a.focus(); a.select();
  35. document.execCommand("copy");
  36. }
  37.  
  38. if(textarea||input){//Do nothing}
  39. else a.remove();
  40. }
  41.  
  42. /* Text argument can be a string or a textarea/input element;
  43. let a= document.querySelector("textarea");
  44. let b= "hello";
  45. copyText(a); or copy(b)
  46. */
  47.  
  48.  
  49.  
  50.  
  51. //--------------------------------------------
  52.  
  53.  
  54.  
  55.  
  56.  
  57. let b= document.querySelector('pre'),
  58.     c= 'i am stupid';
  59.  
  60. b.addEventListener('copy',
  61. function(e){
  62. e.clipboardData.setData('text', c);
  63. e.preventDefault();
  64. });
  65.  
  66. b.onclick= function() {
  67. try{ navigator.clipboard.writeText(c);
  68. alert('Copied!');
  69. }
  70. catch(err){
  71.     try{let inp =document.createElement('input');
  72.         document.body.appendChild(inp)
  73.         inp.value= c; inp.select();
  74.         document.execCommand('copy',false);
  75.         inp.remove();
  76.         alert('Copied!!');}
  77.     catch(err){
  78.         try{let e= window.getSelection(),
  79.             f= document.createRange();
  80.             f.selectNodeContents(b);
  81.             e.removeAllRanges();
  82.             e.addRange(f);
  83.             document.execCommand("copy");
  84.             alert('Copied!!!');}
  85.          catch(err){alert("Couldn't copy because: "+ err.message)}
  86.      }
  87. }
  88. };
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement