// Create an editable DIV and append the HTML content you want copiedvar editableDiv = document.createElement("div");with (editableDiv) {contentEditable = true;}editableDiv.appendChild(someContentElement);
// Select the editable content and copy it to the clipboardvar r = document.body.createTextRange();r.moveToElementText(editableDiv);r.select();r.execCommand("Copy");
// Deselect, so the browser doesn't leave the element visibly selectedr.moveToElementText(someHiddenDiv);r.select();
function copyToClipboard(text) {window.prompt("Copy to clipboard: Ctrl+C, Enter", text);}
用户将看到提示框,其中要复制的文本已被选中。现在只需按Ctrl+C和输入(关闭框)即可——瞧!
现在剪贴板复制操作是安全,因为用户手动执行(但以非常简单的方式)。当然,它适用于所有浏览器。
<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>
这是Chase Seibert的回答的扩展,其优点是它适用于IMAGE和TABLE元素,而不仅仅是Internet Explorer 9上的DIV。
if (document.createRange) {// Internet Explorer 9 and modern browsersvar r = document.createRange();r.setStartBefore(to_copy);r.setEndAfter(to_copy);r.selectNode(to_copy);var sel = window.getSelection();sel.addRange(r);document.execCommand('Copy'); // Does nothing on Firefox} else {// Internet Explorer 8 and earlier. This stuff won't work// on Internet Explorer 9.// (unless forced into a backward compatibility mode,// or selecting plain divs, not img or table).var r = document.body.createTextRange();r.moveToElementText(to_copy);r.select()r.execCommand('Copy');}
function clipBoard(sCommand) {var oRange = contentDocument.createRange();oRange.setStart(startNode, startOffset);oRange.setEnd(endNode, endOffset);
/* This is where the actual selection happens.in the above, startNode and endNode areDOM nodes defining the beginning andend of the "selection" respectively.
startOffset and endOffset are constantsthat are defined as follows:
END_TO_END: 2END_TO_START: 3NODE_AFTER: 1NODE_BEFORE: 0NODE_BEFORE_AND_AFTER: 2NODE_INSIDE: 3START_TO_END: 1START_TO_START: 0
And it would be used like oRange.START_TO_END*/
switch(sCommand) {
case "cut":this.oFragment = oRange.extractContents();oRange.collapse();break;
case "copy":this.oFragment = oRange.cloneContents();break;
case "paste":oRange.deleteContents();var cloneFragment = this.oFragment.cloneNode(true)oRange.insertNode(cloneFragment);oRange.collapse();break;}}
function EnybyClipboard() {this.saveSelection = false;this.callback = false;this.pastedText = false;
this.restoreSelection = function() {if (this.saveSelection) {window.getSelection().removeAllRanges();for (var i = 0; i < this.saveSelection.length; i++) {window.getSelection().addRange(this.saveSelection[i]);}this.saveSelection = false;}};
this.copyText = function(text) {var div = $('special_copy');if (!div) {div = new Element('pre', {'id': 'special_copy','style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'});div.injectInside(document.body);}div.set('text', text);if (document.createRange) {var rng = document.createRange();rng.selectNodeContents(div);this.saveSelection = [];var selection = window.getSelection();for (var i = 0; i < selection.rangeCount; i++) {this.saveSelection[i] = selection.getRangeAt(i);}window.getSelection().removeAllRanges();window.getSelection().addRange(rng);setTimeout(this.restoreSelection.bind(this), 100);} else return alert('Copy did not work. :(');};
this.getPastedText = function() {if (!this.pastedText) alert('Nothing to paste. :(');return this.pastedText;};
this.pasteText = function(callback) {var div = $('special_paste');if (!div) {div = new Element('textarea', {'id': 'special_paste','style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'});div.injectInside(document.body);div.addEvent('keyup', function() {if (this.callback) {this.pastedText = $('special_paste').get('value');this.callback.call(null, this.pastedText);this.callback = false;this.pastedText = false;setTimeout(this.restoreSelection.bind(this), 100);}}.bind(this));}div.set('value', '');if (document.createRange) {var rng = document.createRange();rng.selectNodeContents(div);this.saveSelection = [];var selection = window.getSelection();for (var i = 0; i < selection.rangeCount; i++) {this.saveSelection[i] = selection.getRangeAt(i);}window.getSelection().removeAllRanges();window.getSelection().addRange(rng);div.focus();this.callback = callback;} else return alert('Failed to paste. :(');};}
用法:
enyby_clip = new EnybyClipboard(); // Init
enyby_clip.copyText('some_text'); // Place this in the Ctrl+C handler and return true;
enyby_clip.pasteText(function callback(pasted_text) {alert(pasted_text);}); // Place this in Ctrl+V handler and return true;
<?phpclass Ajax extends CI_Controller {
public function foo_copy($val){$this->session->set_userdata(array('clipboard_val' => $val));}
public function foo_paste(){echo $this->session->userdata('clipboard_val');exit();}}?>
function readTextFromClipboardInChromeExtension() {var ta = $('<textarea/>');$('body').append(ta);ta.focus();document.execCommand('paste');var text = ta.val();ta.blur();ta.remove();return text;}
function fallbackCopyTextToClipboard(text) {var textArea = document.createElement("textarea");textArea.value = text;
// Avoid scrolling to bottomtextArea.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);});
通过GoogleChrome44、Firefox 42.0a1和Internet Explorer 11.0.8600.17814进行测试。
(可能无法在本网站嵌入工作,阅读上面的“重要”说明)
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>
<button id='markup-copy'>Copy Button</button>
<script>document.getElementById('markup-copy').addEventListener('click', function() {clipboard.copy({'text/plain': 'Markup text. Paste me into a rich text editor.','text/html': '<i>here</i> is some <b>rich text</b>'}).then(function(){console.log('success'); },function(err){console.log('failure', err);});
});</script>
/*** Copies the current selected text to the SO clipboard* This method must be called from an event to work with `execCommand()`* @param {String} text Text to copy* @param {Boolean} [fallback] Set to true shows a prompt* @return Boolean Returns `true` if the text was copied or the user clicked on accept (in prompt), `false` otherwise*/var CopyToClipboard = function(text, fallback){var fb = function () {$t.remove();if (fallback !== undefined && fallback) {var fs = 'Please, copy the following text:';if (window.prompt(fs, text) !== null) return true;}return false;};var $t = $('<textarea />');$t.val(text).css({width: '100px',height: '40px'}).appendTo('body');$t.select();try {if (document.execCommand('copy')) {$t.remove();return true;}fb();}catch (e) {fb();}};
new ClipboardJS("#btn1");
document.querySelector("#btn2").addEventListener("click", () => document.querySelector("#btn1").dataset.clipboardText = Math.random());
<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js"></script>
<button id="btn1" data-clipboard-text="Text to copy goes here">Copy to clipboard</button><button id="btn2">Click here to change data-clipboard-text</button>
<br /><br />
<input type="text" placeholder="Paste here to see clipboard" />
function selectElementContents(el) {// Copy textarea, pre, div, etc.if (document.body.createTextRange) {// Internet Explorervar textRange = document.body.createTextRange();textRange.moveToElementText(el);textRange.select();textRange.execCommand("Copy");}else if (window.getSelection && document.createRange) {// Non-Internet Explorervar range = document.createRange();range.selectNodeContents(el);var sel = window.getSelection();sel.removeAllRanges();sel.addRange(range);try {var successful = document.execCommand('copy');var msg = successful ? 'successful' : 'unsuccessful';console.log('Copy command was ' + msg);}catch (err) {console.log('Oops, unable to copy');}}} // end function selectElementContents(el)
function make_copy_button(el) {var copy_btn = document.createElement('input');copy_btn.type = "button";el.parentNode.insertBefore(copy_btn, el.nextSibling);copy_btn.onclick = function() {selectElementContents(el);};
if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {// Copy works with Internet Explorer 4+, Chrome 42+, Firefox 41+, Opera 29+copy_btn.value = "Copy to Clipboard";}else {// Select only for Safari and older Chrome, Firefox and Operacopy_btn.value = "Select All (then press Ctrl + C to Copy)";}}/* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy,but there was a bug in Chrome versions 42 to 47 that makes it return "false". So in thoseversions of Chrome feature detection does not work!See https://code.google.com/p/chromium/issues/detail?id=476508*/
make_copy_button(document.getElementById("markup"));
<pre id="markup">Text that can be copied or selected with cross browser support.</pre>
// 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);}}}
<html><body><button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button><script src="ZeroClipboard.js"></script><script src="main.js"></script></body></html>
javascript
var client = new ZeroClipboard(document.getElementById("copy-button"));
client.on("ready", function (readyEvent) {// alert( "ZeroClipboard SWF is ready!" );
client.on("aftercopy", function (event) {// `this` === `client`// `event.target` === the element that was clickedevent.target.style.display = "none";alert("Copied text to clipboard: " + event.data["text/plain"]);});});
function copyToClipboard(sID) {var aField = document.getElementById("hiddenField");
aField.hidden = false;aField.value = document.getElementById(sID).textContent;aField.select();document.execCommand("copy");alert("Following text has been copied to the clipboard.\n\n" + aField.value);aField.hidden = true;}
jQuery('#copy').on('click', function () {copyToClipboard();});
function copyToClipboard() {var target = jQuery('#hidden_text');
// Make it visible, so can be focusedtarget.attr('type', 'text');target.focus();// Select all the texttarget[0].setSelectionRange(0, target.val().length);
// Copy the selectionvar succeed;try {succeed = document.execCommand("copy");}catch (e) {succeed = false;}
// Hide input againtarget.attr('type', 'hidden');
return succeed;}
window.copyToClipboard = function(text) {// Internet Explorer specificif (window.clipboardData && window.clipboardData.setData) {return clipboardData.setData("Text", text);}
// All other modern browserstarget = document.createElement("textarea");target.style.position = "absolute";target.style.left = "-9999px";target.style.top = "0";target.textContent = text;document.body.appendChild(target);target.focus();target.setSelectionRange(0, target.value.length);
// Copy the selection of fall back to prompttry {document.execCommand("copy");target.remove();console.log('Copied to clipboard: "'+text+'"');}catch(e) {console.log("Can't copy string on this browser. Try to use Chrome, Firefox or Opera.")window.prompt("Copy to clipboard: Ctrl+C, Enter", text);}}
<script>$(document).ready(function(){$("#selectMe").selectText(); // Hightlight / select the text$("#selectMe").selectText(false); // Clear the selection
$("#copyMe").copyText(); // Copy text to clipboard});</script>
let textarea = document.createElement('textarea');textarea.setAttribute('type', 'hidden');textarea.textContent = 'the string you want to copy';document.body.appendChild(textarea);textarea.select();document.execCommand('copy');
function myFunction() {/* Get the text field */var copyText = document.getElementById("myInput");
/* Select the text field */copyText.select();
/* Copy the text inside the text field */document.execCommand("Copy");
/* Alert the copied text */alert("Copied the text: " + copyText.value);}
<!-- The text field --><input type="text" value="Hello Friend" id="myInput">
<!-- The button used to copy the text --><button onclick="myFunction()">Copy text</button>
function copyToClp(txt){var m = document;txt = m.createTextNode(txt);var w = window;var b = m.body;b.appendChild(txt);if (b.createTextRange) {var d = b.createTextRange();d.moveToElementText(txt);d.select();m.execCommand('copy');}else {var d = m.createRange();var g = w.getSelection;d.selectNodeContents(txt);g().removeAllRanges();g().addRange(d);m.execCommand('copy');g().removeAllRanges();}txt.remove();}
function copytoclipboard(element) {
var $temp = $("<input>");$("body").append($temp);$temp.val('0' + element).select();document.execCommand("copy");$temp.remove();}
此解决方案已找到这里。Internet Explorer 8及更早版本不支持document.execCommand("copy");。
const copyBtn = document.getElementById("copyBtn");const input = document.getElementById("input");
function copyText() {const value = input.value;
input.select(); // selects the input variable as the text to be copiedinput.setSelectionRange(0, 99999); // this is used to set the selection range for mobile devices
document.execCommand("copy"); // copies the selected text
alert("Copied the text " + value); // displays the copied text in a prompt}
copyBtn.onmousedown = function () {copyText();}
<input type="text" id="input" placeholder="Type text to copy... "/><button id="copyBtn">Copy</button>
function CopyToNotepad(id){var r = document.createRange();r.selectNode(document.getElementById(id));window.getSelection().removeAllRanges();window.getSelection().addRange(r);document.execCommand('copy');window.getSelection().removeAllRanges();}
// Copies a string to clipboard// Uses navigator API if available, else uses execCommand (deprecated)// Returns a boolean if copy was successful// See: https://stackoverflow.com/q/400212/4907950async function copyText(str) {console.log('Copying', str);if (!navigator.clipboard) {// fallbacklet input = document.createElement('textarea');input.innerHTML = str;document.body.appendChild(input);input.focus();input.select();let result;
try {result = document.execCommand('copy');console.log('Fallback: Copying text command was ' + (result ? 'successful' : 'unsuccessful'));} catch (err) {console.error('Fallback: Could not copy text: ', err);}document.body.removeChild(input);return result;}const result = navigator.clipboard.writeText(str).then(function () {console.log('Async: Copying to clipboard was successful');return true;},function (err) {console.error('Async: Could not copy text: ', err);return false;});return result;
<!DOCTYPE html><html><body>
<p>Click on the button to copy the text from the text field. Try to pastethe text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>
<input type="text" value="Hello World" id="myInput"><button onclick="myFunction()">Copy text</button>
<script>function myFunction() {/* Get the text field */var copyText = document.getElementById("myInput");
/* Select the text field */copyText.select();copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */navigator.clipboard.writeText(copyText.value);
/* Alert the copied text */alert("Copied the text: " + copyText.value);}
</script>
</body></html>
async function copyTextToClipboard(textToCopy) {try {await navigator.clipboard.writeText(textToCopy);console.log('copied to clipboard')} catch (error) {console.log('failed to copy to clipboard. error=' + error);}}