Comment puis-je copier le presse-papier en JavaScript

Mots clés : javascriptclipboardcopy-pastejavascript

meilleur 5 Réponses Comment puis-je copier le presse-papier en JavaScript

vote vote

91

function fallbackCopyTextToClipboard(text) {   var textArea = document.createElement("textarea");   textArea.value = text;      // Avoid scrolling to bottom   textArea.style.top = "0";   textArea.style.left = "0";   textArea.style.position = "fixed";    document.body.appendChild(textArea);   textArea.focus();   textArea.select();    try {     var successful = document.execCommand('copy');     var msg = successful ? 'successful' : 'unsuccessful';     console.log('Fallback: Copying text command was ' + msg);   } catch (err) {     console.error('Fallback: Oops, unable to copy', err);   }    document.body.removeChild(textArea); } function copyTextToClipboard(text) {   if (!navigator.clipboard) {     fallbackCopyTextToClipboard(text);     return;   }   navigator.clipboard.writeText(text).then(function() {     console.log('Async: Copying to clipboard was successful!');   }, function(err) {     console.error('Async: Could not copy text: ', err);   }); }  var copyBobBtn = document.querySelector('.js-copy-bob-btn'),   copyJaneBtn = document.querySelector('.js-copy-jane-btn');  copyBobBtn.addEventListener('click', function(event) {   copyTextToClipboard('Bob'); });   copyJaneBtn.addEventListener('click', function(event) {   copyTextToClipboard('Jane'); });
<div style="display:inline-block; vertical-align:top;">   <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />   <button class="js-copy-jane-btn">Set clipboard to JANE</button> </div> <div style="display:inline-block;">   <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:    </textarea> </div>
var text = "Example text to appear on clipboard"; navigator.clipboard.writeText(text).then(function() {   console.log('Async: Copying to clipboard was successful!'); }, function(err) {   console.error('Async: Could not copy text: ', err); }); 
var copyTextareaBtn = document.querySelector('.js-textareacopybtn');  copyTextareaBtn.addEventListener('click', function(event) {   var copyTextarea = document.querySelector('.js-copytextarea');   copyTextarea.focus();   copyTextarea.select();    try {     var successful = document.execCommand('copy');     var msg = successful ? 'successful' : 'unsuccessful';     console.log('Copying text command was ' + msg);   } catch (err) {     console.log('Oops, unable to copy');   } });
<p>   <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>   <textarea class="js-copytextarea">Hello I'm some text</textarea> </p>
function copyTextToClipboard(text) {   var textArea = document.createElement("textarea");    //   // *** This styling is an extra step which is likely not required. ***   //   // Why is it here? To ensure:   // 1. the element is able to have focus and selection.   // 2. if the element was to flash render it has minimal visual impact.   // 3. less flakyness with selection and copying which **might** occur if   //    the textarea element is not visible.   //   // The likelihood is the element won't even render, not even a   // flash, so some of these are just precautions. However in   // Internet Explorer the element is visible whilst the popup   // box asking the user for permission for the web page to   // copy to the clipboard.   //    // Place in the top-left corner of screen regardless of scroll position.   textArea.style.position = 'fixed';   textArea.style.top = 0;   textArea.style.left = 0;    // Ensure it has a small width and height. Setting to 1px / 1em   // doesn't work as this gives a negative w/h on some browsers.   textArea.style.width = '2em';   textArea.style.height = '2em';    // We don't need padding, reducing the size if it does flash render.   textArea.style.padding = 0;    // Clean up any borders.   textArea.style.border = 'none';   textArea.style.outline = 'none';   textArea.style.boxShadow = 'none';    // Avoid flash of the white box if rendered for any reason.   textArea.style.background = 'transparent';     textArea.value = text;    document.body.appendChild(textArea);   textArea.focus();   textArea.select();    try {     var successful = document.execCommand('copy');     var msg = successful ? 'successful' : 'unsuccessful';     console.log('Copying text command was ' + msg);   } catch (err) {     console.log('Oops, unable to copy');   }    document.body.removeChild(textArea); }   var copyBobBtn = document.querySelector('.js-copy-bob-btn'),   copyJaneBtn = document.querySelector('.js-copy-jane-btn');  copyBobBtn.addEventListener('click', function(event) {   copyTextToClipboard('Bob'); });   copyJaneBtn.addEventListener('click', function(event) {   copyTextToClipboard('Jane'); });
<div style="display:inline-block; vertical-align:top;">   <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />   <button class="js-copy-jane-btn">Set clipboard to JANE</button> </div> <div style="display:inline-block;">   <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:    </textarea> </div>
vote vote

81

function copyToClipboard(text) {   window.prompt("Copy to clipboard: Ctrl+C, Enter", text); } 
<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>  <script>   function copyToClipboard(text) {     window.prompt("Copy to clipboard: Ctrl+C, Enter", text);   } </script>
vote vote

72

// Copies a string to the clipboard. Must be called from within an // event handler such as click. May return false if it failed, but // this is not always possible. Browser support for Chrome 43+, // Firefox 42+, Safari 10+, Edge and Internet Explorer 10+. // Internet Explorer: The clipboard feature may be disabled by // an administrator. By default a prompt is shown the first // time the clipboard is used (per session). function copyToClipboard(text) {     if (window.clipboardData && window.clipboardData.setData) {         // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.         return window.clipboardData.setData("Text", text);      }     else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {         var textarea = document.createElement("textarea");         textarea.textContent = text;         textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.         document.body.appendChild(textarea);         textarea.select();         try {             return document.execCommand("copy");  // Security exception may be thrown by some browsers.         }         catch (ex) {             console.warn("Copy to clipboard failed.", ex);             return prompt("Copy to clipboard: Ctrl+C, Enter", text);         }         finally {             document.body.removeChild(textarea);         }     } } 
vote vote

60

function copy(text) {     var input = document.createElement('input');     input.setAttribute('value', text);     document.body.appendChild(input);     input.select();     var result = document.execCommand('copy');     document.body.removeChild(input);     return result;  } 
function copy(text) {     var input = document.createElement('textarea');     input.innerHTML = text;     document.body.appendChild(input);     input.select();     var result = document.execCommand('copy');     document.body.removeChild(input);     return result; } 
vote vote

60

    <script type="text/javascript">          function select_all(obj) {              var text_val=eval(obj);              text_val.focus();              text_val.select();              r = text_val.createTextRange();              if (!r.execCommand) return; // feature detection              r.execCommand('copy');          }      </script>      <input value="http://www.sajithmr.com"       onclick="select_all(this)" name="url" type="text" />

Questions similaires