Related
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I copy text to the clipboard (multi-browser)?
Related: How does Trello access the user's clipboard?
Overview
There are three primary browser APIs for copying to the clipboard:
Async Clipboard API [navigator.clipboard.writeText]
Text-focused portion available in Chrome 66 (March 2018)
Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
Text can be copied to the clipboard directly from a variable.
Only supported on pages served over HTTPS.
In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
document.execCommand('copy') (deprecated) đź‘Ž
Most browsers support this as of ~April 2015 (see Browser Support below).
Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
Text is read from the DOM and placed on the clipboard.
During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
Overriding the copy event
See Clipboard API documentation on Overriding the copy event.
Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
Not covered here as it doesn't directly answer the question.
General development notes
Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.
IMPORTANT (noted here 2020/02/20)
Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).
To develop create your own web page, serve that page over an HTTPS connection to test and develop against.
Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/
Async + Fallback
Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.
Here is a simple example (may not work embedded in this site, read "important" note above):
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>
(codepen.io example may not work, read "important" note above)
Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011
Async Clipboard API
MDN Reference
Chrome 66 announcement post (March 2018)
Reference Async Clipboard API draft documentation
Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.
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);
});
document.execCommand('copy')
The rest of this post goes into the nuances and detail of the document.execCommand('copy') API.
Browser Support
The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates: (deprecated) đź‘Ž
Internet Explorer 10+ (although this document indicates some support was there from Internet Explorer 5.5+).
Google Chrome 43+ (~April 2015)
Mozilla Firefox 41+ (shipping ~September 2015)
Opera 29+ (based on Chromium 42, ~April 2015)
Simple Example
(may not work embedded in this site, read "important" note above)
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>
Complex Example: Copy to clipboard without displaying input
The above simple example works great if there is a textarea or input element visible on the screen.
In some cases, you might wish to copy text to the clipboard without displaying an input / textarea element. This is one example of a way to work around this (basically insert an element, copy to clipboard, remove element):
Tested with Google Chrome 44, Firefox 42.0a1, and Internet Explorer 11.0.8600.17814.
(may not work embedded in this site, read "important" note above)
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>
Additional notes
Only works if the user takes an action
All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the user's clipboard when they don't expect it.
See the Google Developers post here for more info.
Clipboard API
Note the full Clipboard API draft specification can be found here:
https://w3c.github.io/clipboard-apis/
Is it supported?
document.queryCommandSupported('copy') should return true if the command "is supported by the browser".
and document.queryCommandEnabled('copy') return true if the document.execCommand('copy') will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.
However, as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned true from document.queryCommandSupported('copy') if the command was called from a user-initiated thread.
Note compatibility detail below.
Browser Compatibility Detail
Whilst a simple call to document.execCommand('copy') wrapped in a try/catch block called as a result of a user click will get you the most compatibility use the following has some provisos:
Any call to document.execCommand, document.queryCommandSupported or document.queryCommandEnabled should be wrapped in a try/catch block.
Different browser implementations and browser versions throw differing types of exceptions when called instead of returning false.
Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.
Automatic copying to the clipboard may be dangerous, and therefore most browsers (except Internet Explorer) make it very difficult. Personally, I use the following simple trick:
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl+C and Enter (to close the box) -- and voila!
Now the clipboard copy operation is safe, because the user does it manually (but in a pretty straightforward way). Of course, it works in all browsers.
<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>
The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).
Create a textarea and set its contents to the text you want copied to the clipboard.
Append the textarea to the DOM.
Select the text in the textarea.
Call document.execCommand("copy")
Remove the textarea from the dom.
Note: you will not see the textarea, as it is added and removed within the same synchronous invocation of Javascript code.
Some things to watch out for if you are implementing this yourself:
For security reasons, this can only called from an event handler such as click (Just as with opening windows).
Internet Explorer will show a permission dialog the first time the clipboard is updated.
Internet Explorer, and Edge will scroll when the textarea is focused.
execCommand() may throw in some cases.
Newlines and tabs can get swallowed unless you use a textarea. (Most articles seem to recommend using a div)
The textarea will be visible while the Internet Explorer dialog is shown, you either need to hide it, or use the Internet Explorer specific clipboardData API.
In Internet Explorer system administrators can disable the clipboard API.
The function below should handle all of the following issues as cleanly as possible. Please leave a comment if you find any problems or have any suggestions for improving it.
// 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);
}
}
}
https://jsfiddle.net/fx6a6n6x/
Here is my take on that one...
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;
}
#korayem: Note that using html input field won't respect line breaks \n and will flatten any text into a single line.
As mentioned by #nikksan in the comments, using textarea will fix the problem as follows:
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;
}
Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:
<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" />
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.
It was written by a cofounder of GitHub. Example Flash embed code below:
<object
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
width="110"
height="14"
id="clippy">
<param name="movie" value="/flash/clippy.swf"/>
<param name="allowScriptAccess" value="always"/>
<param name="quality" value="high"/>
<param name="scale" value="noscale"/>
<param NAME="FlashVars" value="text=#{text}"/>
<param name="bgcolor" value="#{bgcolor}"/>
<embed
src="/flash/clippy.swf"
width="110"
height="14"
name="clippy"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
FlashVars="text=#{text}"
bgcolor="#{bgcolor}"/>
</object>
Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.
I have recently written a technical blog post on this very problem (I work at Lucidchart and we recently did an overhaul on our clipboard).
Copying plain text to the clipboard is relatively simple, assuming you attempt to do it during a system copy event (user presses Ctrl+C or uses the browser's menu).
var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 ||
navigator.userAgent.toLowerCase().indexOf("trident") != -1);
document.addEventListener('copy', function(e) {
var textToPutOnClipboard = "This is some text";
if (isIe) {
window.clipboardData.setData('Text', textToPutOnClipboard);
} else {
e.clipboardData.setData('text/plain', textToPutOnClipboard);
}
e.preventDefault();
});
Putting text on the clipboard not during a system copy event is much more difficult. It looks like some of these other answers reference ways to do it via Flash, which is the only cross-browser way to do it (so far as I understand).
Other than that, there are some options on a browser-by-browser basis.
This is the most simple in Internet Explorer, where you can access the clipboardData object at anytime from JavaScript via:
window.clipboardData
(When you attempt to do this outside of a system cut, copy, or paste event, however, Internet Explorer will prompt the user to grant the web application clipboard permission.)
In Chrome, you can create a Chrome extension that will give you clipboard permissions (this is what we do for Lucidchart). Then for users with your extension installed you'll just need to fire the system event yourself:
document.execCommand('copy');
It looks like Firefox has some options that allow users to grant permissions to certain sites to access the clipboard, but I haven't tried any of these personally.
I like this one:
<input onclick="this.select();" type='text' value='copy me' />
If a user doesn't know how to copy text in their OS, then it's likely they don't know how to paste either. So just have it automatically selected, leaving the rest to the user.
clipboard.js is a small, non-Flash, utility that allows copying of text or HTML data to the clipboard. It's very easy to use, just include the .js and use something like this:
<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>
clipboard.js is also on GitHub.
Note: This has been deprecated now. Migrate to here.
In 2018, here's how you can go about it:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
It is used in my Angular 6+ code like so:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
If I pass in a string, it copies it. If nothing, it copies the page's URL.
More gymnastics to the clipboard stuff can be done too. See more information here:
Unblocking Clipboard Access
I use this very successfully (without jQuery or any other framework).
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();
}
Warning
Tabs are converted to spaces (at least in Chrome).
ZeroClipboard is the best cross-browser solution I've found:
<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
If you need non-Flash support for iOS you just add a fall-back:
clip.on( 'noflash', function ( client, args ) {
$("#copy").click(function(){
var txt = $(this).attr('data-clipboard-text');
prompt ("Copy link, then click OK.", txt);
});
});
http://zeroclipboard.org/
https://github.com/zeroclipboard/ZeroClipboard
Since Chrome 42+ and Firefox 41+ now support the document.execCommand('copy') command, I created a couple of functions for a cross-browser copy-to-clipboard ability using a combination of Tim Down's old answer and Google Developer's answer:
function selectElementContents(el) {
// Copy textarea, pre, div, etc.
if (document.body.createTextRange) {
// Internet Explorer
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
textRange.execCommand("Copy");
}
else if (window.getSelection && document.createRange) {
// Non-Internet Explorer
var 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 Opera
copy_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 those
versions 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>
Best and Easy way in JavaScript/TypeScript use this command
navigator.clipboard.writeText(textExample);
just pass your value what you want to copy to clipboard in textExample
I've put together what I think is the best one.
Uses cssText to avoid exceptions in Internet Explorer as opposed to style directly.
Restores selection if there was one
Sets read-only so the keyboard doesn't come up on mobile devices
Has a workaround for iOS so that it actually works as it normally blocks execCommand.
Here it is:
const copyToClipboard = (function initClipboardText() {
const textarea = document.createElement('textarea');
// Move it off-screen.
textarea.style.cssText = 'position: absolute; left: -99999em';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
return function setClipboardText(text) {
textarea.value = text;
// Check if there is any content selected previously.
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
// iOS Safari blocks programmatic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
}
else {
textarea.select();
}
try {
const result = document.execCommand('copy');
// Restore previous selection.
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return result;
}
catch (err) {
console.error(err);
return false;
}
};
})();
Usage: copyToClipboard('some text')
The other methods will copy plain text to the clipboard. To copy HTML (i.e., you can paste results into a WYSIWYG editor), you can do the following in Internet Explorer only. This is is fundamentally different from the other methods, as the browser actually visibly selects the content.
// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
contentEditable = true;
}
editableDiv.appendChild(someContentElement);
// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");
// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();
I found the following solution:
The on-key-down handler creates a "pre" tag. We set the content to copy to this tag, and then make a selection on this tag and return true in the handler. This calls the standard handler of Chrome and copies selected text.
And if you need it, you may set the timeout for a function for restoring the previous selection. My implementation on MooTools:
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. :(');
};
}
Usage:
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;
On paste, it creates a textarea and works the same way.
PS: Maybe this solution can be used for creating a full cross-browser solution without Flash. It works in Firefox and Chrome.
This code tested # 2021 May . Work on Chrome , IE , Edge. 'message' parameter on below is the string value you want to copy.
<script type="text/javascript">
function copyToClipboard(message) {
var textArea = document.createElement("textarea");
textArea.value = message;
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Unable to copy value , error : ' + err.message);
}
document.body.removeChild(textArea);
}
</script>
This works straight away, using the newest Clipboard API, and a user interaction:
copy.addEventListener("pointerdown", () => navigator.clipboard.writeText("Hello World!"))
<button id="copy">Copy Hello World!</button>
Copy text from HTML input to the clipboard:
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>
Note: The document.execCommand() method is not supported in Internet Explorer 9 and earlier.
Source: W3Schools - Copy Text to Clipboard
Best Way to Copy the text inside the text field.
Use navigator.clipboard.writeText.
<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}
</script>
I had the same problem building a custom grid edit from (something like Excel) and compatibility with Excel. I had to support selecting multiple cells, copying and pasting.
Solution: create a textarea where you will be inserting data for the user to copy (for me when the user is selecting cells), set focus on it (for example, when user press Ctrl) and select the whole text.
So, when the user hit Ctrl+C he/she gets copied cells he/she selected. After testing just resizing the textarea to one pixel (I didn't test if it will be working on display:none). It works nicely on all browsers, and it is transparent to the user.
Pasting - you could do same like this (differs on your target) - keep focus on textarea and catch paste events using onpaste (in my project I use textareas in cells to edit).
I can't paste an example (commercial project), but you get the idea.
This is an expansion of Chase Seibert's answer, with the advantage that it will work for IMAGE and TABLE elements, not just DIVs on Internet Explorer 9.
if (document.createRange) {
// Internet Explorer 9 and modern browsers
var 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');
}
I have used clipboard.js.
We can get it on npm:
npm install clipboard --save
And also on Bower
bower install clipboard --save
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" />
More usage & examples are at https://zenorocha.github.io/clipboard.js/.
My bad. This only works in Internet Explorer.
Here's yet another way to copy text:
<p>
<a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>
I am loath to add another answer on this, but to help rookies like me, and because this is the top Google result I will.
In 2022 to copy text to the clipboard you use one line.
navigator.clipboard.writeText(textToCopy);
This returns a Promise that is resolved if it copies, or rejects if it fails.
A full working function is this:
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);
}
}
WARNING! If you have Chrome Dev Tools open while testing this it will fail because for the browser to enable the clipboard, it requires you to have the window in focus. This is to prevent random websites changing your clipboard if you don't want it. Dev Tools steals this focus so close Dev Tools and your test will work.
If you want to copy other things (images, etc) to the clipboard, look at these docs.
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
This is well supported enough in browsers you can use it. If you are worried about Firefox, use a Permissions Query to show or hide the button if the browser supports it. https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
Here is the simple Ajax/session based clipboard for the same website.
Note that the session must be enabled & valid and this solution works for the same site. I tested it on CodeIgniter, but I ran into session/Ajax problem, but this solved that problem too. If you don't want to play with sessions, use a database table.
JavaScript/jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#copy_btn_id").click(function(){
$.post("<?php echo base_url();?>ajax/foo_copy/"+$(this).val(), null,
function(data){
// Copied successfully
}, "html"
);
});
$("#paste_btn_id").click(function() {
$.post("<?php echo base_url();?>ajax/foo_paste/", null,
function(data) {
$('#paste_btn_id').val(data);
}, "html"
);
});
});
</script>
HTML content
<input type='text' id='copy_btn_id' onclick='this.select();' value='myvalue' />
<input type='text' id='paste_btn_id' value='' />
PHP code
<?php
class 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();
}
}
?>
This code works in all browsers except for IE. Anything I can do to add support for it?
<script type="text/javascript">
$(document).ready(function() {
var currentArrayNum = 2;
$('#names').on({
blur: function() {
currentArrayNum += 1;
var name = $("<p><input class='input' type='text' name='guests[]' value='' /></p>");
var nullFields = 0;
$(this).closest('div#names').find('input.input').each(function(){
if($(this).val() == ""){
nullFields++;
}
});
console.log(nullFields);
if(nullFields <= 1){
$('#names').append(name.fadeIn(500));
$('#leftbox').scrollTop($('#leftbox')[0].scrollHeight);
}
}
}, 'input');
});
</script>
It should mean that extra input fields are added. You can see it in action (in FF, Chrome, Safari etc) under 'Enter names for the guestlist' here.
EDIT
Tested in IE9 but doesn't work for me.
I should also ask if there's a way of testing in different versions of IE (and othe browsers) on a Mac?
Note that in some (all?) versions of IE, you need to have developer ("F12") tools open for console.log to work, otherwise console is undefined and so console.log() throws an error.
That may be your issue.
I know your question is about a week old but Im not sure if you found a solution or the reason for the cross-browser issues. I was recently working on a custom modal pop up window and I needed to find my scrollTop. Trust me, I love jQuery to death and I use it everyday but sometimes you need to use some good ol' javaScript. I.E accesses the body of the DOM differently than say Chrome or FF.
//I.E.
document.documentElement.scrollTop;
//Chrome, FF, etc.
document.body.scrollTop;
Basically, create a script that detects the user's browser and then include a conditional statement that will assign the value the appropriate way.
//Detect Browser
if (clientBrowser == "IE") {
currTopPos = document.documentElement.scrollTop;
} else {
currTopPos = document.body.scrollTop;
}
I created a script for one of the current projects Im working on, let me know if you would like to take a look at it.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
How do I copy text to the clipboard (multi-browser)?
Related: How does Trello access the user's clipboard?
Overview
There are three primary browser APIs for copying to the clipboard:
Async Clipboard API [navigator.clipboard.writeText]
Text-focused portion available in Chrome 66 (March 2018)
Access is asynchronous and uses JavaScript Promises, can be written so security user prompts (if displayed) don't interrupt the JavaScript in the page.
Text can be copied to the clipboard directly from a variable.
Only supported on pages served over HTTPS.
In Chrome 66 pages inactive tabs can write to the clipboard without a permissions prompt.
document.execCommand('copy') (deprecated) đź‘Ž
Most browsers support this as of ~April 2015 (see Browser Support below).
Access is synchronous, i.e. stops JavaScript in the page until complete including displaying and user interacting with any security prompts.
Text is read from the DOM and placed on the clipboard.
During testing ~April 2015 only Internet Explorer was noted as displaying permissions prompts whilst writing to the clipboard.
Overriding the copy event
See Clipboard API documentation on Overriding the copy event.
Allows you to modify what appears on the clipboard from any copy event, can include other formats of data other than plain text.
Not covered here as it doesn't directly answer the question.
General development notes
Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (document.execCommand('copy')) to access the clipboard see below for more detail.
IMPORTANT (noted here 2020/02/20)
Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).
To develop create your own web page, serve that page over an HTTPS connection to test and develop against.
Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/
Async + Fallback
Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the document.execCommand('copy') method to get good browser coverage.
Here is a simple example (may not work embedded in this site, read "important" note above):
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>
(codepen.io example may not work, read "important" note above)
Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011
Async Clipboard API
MDN Reference
Chrome 66 announcement post (March 2018)
Reference Async Clipboard API draft documentation
Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.
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);
});
document.execCommand('copy')
The rest of this post goes into the nuances and detail of the document.execCommand('copy') API.
Browser Support
The JavaScript document.execCommand('copy') support has grown, see the links below for browser updates: (deprecated) đź‘Ž
Internet Explorer 10+ (although this document indicates some support was there from Internet Explorer 5.5+).
Google Chrome 43+ (~April 2015)
Mozilla Firefox 41+ (shipping ~September 2015)
Opera 29+ (based on Chromium 42, ~April 2015)
Simple Example
(may not work embedded in this site, read "important" note above)
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>
Complex Example: Copy to clipboard without displaying input
The above simple example works great if there is a textarea or input element visible on the screen.
In some cases, you might wish to copy text to the clipboard without displaying an input / textarea element. This is one example of a way to work around this (basically insert an element, copy to clipboard, remove element):
Tested with Google Chrome 44, Firefox 42.0a1, and Internet Explorer 11.0.8600.17814.
(may not work embedded in this site, read "important" note above)
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>
Additional notes
Only works if the user takes an action
All document.execCommand('copy') calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the user's clipboard when they don't expect it.
See the Google Developers post here for more info.
Clipboard API
Note the full Clipboard API draft specification can be found here:
https://w3c.github.io/clipboard-apis/
Is it supported?
document.queryCommandSupported('copy') should return true if the command "is supported by the browser".
and document.queryCommandEnabled('copy') return true if the document.execCommand('copy') will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.
However, as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned true from document.queryCommandSupported('copy') if the command was called from a user-initiated thread.
Note compatibility detail below.
Browser Compatibility Detail
Whilst a simple call to document.execCommand('copy') wrapped in a try/catch block called as a result of a user click will get you the most compatibility use the following has some provisos:
Any call to document.execCommand, document.queryCommandSupported or document.queryCommandEnabled should be wrapped in a try/catch block.
Different browser implementations and browser versions throw differing types of exceptions when called instead of returning false.
Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.
Automatic copying to the clipboard may be dangerous, and therefore most browsers (except Internet Explorer) make it very difficult. Personally, I use the following simple trick:
function copyToClipboard(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}
The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl+C and Enter (to close the box) -- and voila!
Now the clipboard copy operation is safe, because the user does it manually (but in a pretty straightforward way). Of course, it works in all browsers.
<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>
The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).
Create a textarea and set its contents to the text you want copied to the clipboard.
Append the textarea to the DOM.
Select the text in the textarea.
Call document.execCommand("copy")
Remove the textarea from the dom.
Note: you will not see the textarea, as it is added and removed within the same synchronous invocation of Javascript code.
Some things to watch out for if you are implementing this yourself:
For security reasons, this can only called from an event handler such as click (Just as with opening windows).
Internet Explorer will show a permission dialog the first time the clipboard is updated.
Internet Explorer, and Edge will scroll when the textarea is focused.
execCommand() may throw in some cases.
Newlines and tabs can get swallowed unless you use a textarea. (Most articles seem to recommend using a div)
The textarea will be visible while the Internet Explorer dialog is shown, you either need to hide it, or use the Internet Explorer specific clipboardData API.
In Internet Explorer system administrators can disable the clipboard API.
The function below should handle all of the following issues as cleanly as possible. Please leave a comment if you find any problems or have any suggestions for improving it.
// 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);
}
}
}
https://jsfiddle.net/fx6a6n6x/
Here is my take on that one...
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;
}
#korayem: Note that using html input field won't respect line breaks \n and will flatten any text into a single line.
As mentioned by #nikksan in the comments, using textarea will fix the problem as follows:
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;
}
Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:
<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" />
This post is marked obsolete because the content is out of date. It is not currently accepting new interactions.
If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.
It was written by a cofounder of GitHub. Example Flash embed code below:
<object
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
width="110"
height="14"
id="clippy">
<param name="movie" value="/flash/clippy.swf"/>
<param name="allowScriptAccess" value="always"/>
<param name="quality" value="high"/>
<param name="scale" value="noscale"/>
<param NAME="FlashVars" value="text=#{text}"/>
<param name="bgcolor" value="#{bgcolor}"/>
<embed
src="/flash/clippy.swf"
width="110"
height="14"
name="clippy"
quality="high"
allowScriptAccess="always"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer"
FlashVars="text=#{text}"
bgcolor="#{bgcolor}"/>
</object>
Remember to replace #{text} with the text you need copied, and #{bgcolor} with a color.
I have recently written a technical blog post on this very problem (I work at Lucidchart and we recently did an overhaul on our clipboard).
Copying plain text to the clipboard is relatively simple, assuming you attempt to do it during a system copy event (user presses Ctrl+C or uses the browser's menu).
var isIe = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 ||
navigator.userAgent.toLowerCase().indexOf("trident") != -1);
document.addEventListener('copy', function(e) {
var textToPutOnClipboard = "This is some text";
if (isIe) {
window.clipboardData.setData('Text', textToPutOnClipboard);
} else {
e.clipboardData.setData('text/plain', textToPutOnClipboard);
}
e.preventDefault();
});
Putting text on the clipboard not during a system copy event is much more difficult. It looks like some of these other answers reference ways to do it via Flash, which is the only cross-browser way to do it (so far as I understand).
Other than that, there are some options on a browser-by-browser basis.
This is the most simple in Internet Explorer, where you can access the clipboardData object at anytime from JavaScript via:
window.clipboardData
(When you attempt to do this outside of a system cut, copy, or paste event, however, Internet Explorer will prompt the user to grant the web application clipboard permission.)
In Chrome, you can create a Chrome extension that will give you clipboard permissions (this is what we do for Lucidchart). Then for users with your extension installed you'll just need to fire the system event yourself:
document.execCommand('copy');
It looks like Firefox has some options that allow users to grant permissions to certain sites to access the clipboard, but I haven't tried any of these personally.
I like this one:
<input onclick="this.select();" type='text' value='copy me' />
If a user doesn't know how to copy text in their OS, then it's likely they don't know how to paste either. So just have it automatically selected, leaving the rest to the user.
clipboard.js is a small, non-Flash, utility that allows copying of text or HTML data to the clipboard. It's very easy to use, just include the .js and use something like this:
<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>
clipboard.js is also on GitHub.
Note: This has been deprecated now. Migrate to here.
In 2018, here's how you can go about it:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
It is used in my Angular 6+ code like so:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
If I pass in a string, it copies it. If nothing, it copies the page's URL.
More gymnastics to the clipboard stuff can be done too. See more information here:
Unblocking Clipboard Access
I use this very successfully (without jQuery or any other framework).
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();
}
Warning
Tabs are converted to spaces (at least in Chrome).
ZeroClipboard is the best cross-browser solution I've found:
<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
If you need non-Flash support for iOS you just add a fall-back:
clip.on( 'noflash', function ( client, args ) {
$("#copy").click(function(){
var txt = $(this).attr('data-clipboard-text');
prompt ("Copy link, then click OK.", txt);
});
});
http://zeroclipboard.org/
https://github.com/zeroclipboard/ZeroClipboard
Since Chrome 42+ and Firefox 41+ now support the document.execCommand('copy') command, I created a couple of functions for a cross-browser copy-to-clipboard ability using a combination of Tim Down's old answer and Google Developer's answer:
function selectElementContents(el) {
// Copy textarea, pre, div, etc.
if (document.body.createTextRange) {
// Internet Explorer
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
textRange.execCommand("Copy");
}
else if (window.getSelection && document.createRange) {
// Non-Internet Explorer
var 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 Opera
copy_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 those
versions 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>
Best and Easy way in JavaScript/TypeScript use this command
navigator.clipboard.writeText(textExample);
just pass your value what you want to copy to clipboard in textExample
I've put together what I think is the best one.
Uses cssText to avoid exceptions in Internet Explorer as opposed to style directly.
Restores selection if there was one
Sets read-only so the keyboard doesn't come up on mobile devices
Has a workaround for iOS so that it actually works as it normally blocks execCommand.
Here it is:
const copyToClipboard = (function initClipboardText() {
const textarea = document.createElement('textarea');
// Move it off-screen.
textarea.style.cssText = 'position: absolute; left: -99999em';
// Set to readonly to prevent mobile devices opening a keyboard when
// text is .select()'ed.
textarea.setAttribute('readonly', true);
document.body.appendChild(textarea);
return function setClipboardText(text) {
textarea.value = text;
// Check if there is any content selected previously.
const selected = document.getSelection().rangeCount > 0 ?
document.getSelection().getRangeAt(0) : false;
// iOS Safari blocks programmatic execCommand copying normally, without this hack.
// https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
const editable = textarea.contentEditable;
textarea.contentEditable = true;
const range = document.createRange();
range.selectNodeContents(textarea);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
textarea.setSelectionRange(0, 999999);
textarea.contentEditable = editable;
}
else {
textarea.select();
}
try {
const result = document.execCommand('copy');
// Restore previous selection.
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
return result;
}
catch (err) {
console.error(err);
return false;
}
};
})();
Usage: copyToClipboard('some text')
The other methods will copy plain text to the clipboard. To copy HTML (i.e., you can paste results into a WYSIWYG editor), you can do the following in Internet Explorer only. This is is fundamentally different from the other methods, as the browser actually visibly selects the content.
// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
contentEditable = true;
}
editableDiv.appendChild(someContentElement);
// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");
// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();
I found the following solution:
The on-key-down handler creates a "pre" tag. We set the content to copy to this tag, and then make a selection on this tag and return true in the handler. This calls the standard handler of Chrome and copies selected text.
And if you need it, you may set the timeout for a function for restoring the previous selection. My implementation on MooTools:
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. :(');
};
}
Usage:
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;
On paste, it creates a textarea and works the same way.
PS: Maybe this solution can be used for creating a full cross-browser solution without Flash. It works in Firefox and Chrome.
This code tested # 2021 May . Work on Chrome , IE , Edge. 'message' parameter on below is the string value you want to copy.
<script type="text/javascript">
function copyToClipboard(message) {
var textArea = document.createElement("textarea");
textArea.value = message;
textArea.style.opacity = "0";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
alert('Copying text command was ' + msg);
} catch (err) {
alert('Unable to copy value , error : ' + err.message);
}
document.body.removeChild(textArea);
}
</script>
This works straight away, using the newest Clipboard API, and a user interaction:
copy.addEventListener("pointerdown", () => navigator.clipboard.writeText("Hello World!"))
<button id="copy">Copy Hello World!</button>
Copy text from HTML input to the clipboard:
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>
Note: The document.execCommand() method is not supported in Internet Explorer 9 and earlier.
Source: W3Schools - Copy Text to Clipboard
Best Way to Copy the text inside the text field.
Use navigator.clipboard.writeText.
<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}
</script>
I had the same problem building a custom grid edit from (something like Excel) and compatibility with Excel. I had to support selecting multiple cells, copying and pasting.
Solution: create a textarea where you will be inserting data for the user to copy (for me when the user is selecting cells), set focus on it (for example, when user press Ctrl) and select the whole text.
So, when the user hit Ctrl+C he/she gets copied cells he/she selected. After testing just resizing the textarea to one pixel (I didn't test if it will be working on display:none). It works nicely on all browsers, and it is transparent to the user.
Pasting - you could do same like this (differs on your target) - keep focus on textarea and catch paste events using onpaste (in my project I use textareas in cells to edit).
I can't paste an example (commercial project), but you get the idea.
This is an expansion of Chase Seibert's answer, with the advantage that it will work for IMAGE and TABLE elements, not just DIVs on Internet Explorer 9.
if (document.createRange) {
// Internet Explorer 9 and modern browsers
var 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');
}
I have used clipboard.js.
We can get it on npm:
npm install clipboard --save
And also on Bower
bower install clipboard --save
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" />
More usage & examples are at https://zenorocha.github.io/clipboard.js/.
My bad. This only works in Internet Explorer.
Here's yet another way to copy text:
<p>
<a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>
I am loath to add another answer on this, but to help rookies like me, and because this is the top Google result I will.
In 2022 to copy text to the clipboard you use one line.
navigator.clipboard.writeText(textToCopy);
This returns a Promise that is resolved if it copies, or rejects if it fails.
A full working function is this:
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);
}
}
WARNING! If you have Chrome Dev Tools open while testing this it will fail because for the browser to enable the clipboard, it requires you to have the window in focus. This is to prevent random websites changing your clipboard if you don't want it. Dev Tools steals this focus so close Dev Tools and your test will work.
If you want to copy other things (images, etc) to the clipboard, look at these docs.
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
This is well supported enough in browsers you can use it. If you are worried about Firefox, use a Permissions Query to show or hide the button if the browser supports it. https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
Here is the simple Ajax/session based clipboard for the same website.
Note that the session must be enabled & valid and this solution works for the same site. I tested it on CodeIgniter, but I ran into session/Ajax problem, but this solved that problem too. If you don't want to play with sessions, use a database table.
JavaScript/jQuery
<script type="text/javascript">
$(document).ready(function() {
$("#copy_btn_id").click(function(){
$.post("<?php echo base_url();?>ajax/foo_copy/"+$(this).val(), null,
function(data){
// Copied successfully
}, "html"
);
});
$("#paste_btn_id").click(function() {
$.post("<?php echo base_url();?>ajax/foo_paste/", null,
function(data) {
$('#paste_btn_id').val(data);
}, "html"
);
});
});
</script>
HTML content
<input type='text' id='copy_btn_id' onclick='this.select();' value='myvalue' />
<input type='text' id='paste_btn_id' value='' />
PHP code
<?php
class 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();
}
}
?>
So I was browsing the internet one day, and copied a chunk of text "my cool text" and pasted it to facebook, only to see that it changed it to "my cool text - Read More at URL", I was in awe! That's awesome!
So I dove in a little and found some tutorials and such. I took to my own to convert it to a customizable plugin with dozens of options, and it outputs this (or similar based on options):
function copyCopyright() {
var theBody = document.getElementsByTagName("body")[0];
var selection;
selection = window.getSelection();
var copyrightLink = '<br /><br />Read more at: '+document.location.href+'<br /> ©2012 ';
var copytext = selection + copyrightLink;
var extraDiv = document.createElement("div");
extraDiv.style.position="absolute";
extraDiv.style.left="-99999px";
theBody.appendChild(extraDiv);
extraDiv.innerHTML = copytext;
selection.selectAllChildren(extraDiv);
window.setTimeout(function() {
theBody.removeChild(extraDiv);
},0);
}
document.oncopy = copyCopyright;​
works GREAT in Chrome and Firefox, etc. But of COURSE it doesn't work in IE (even IE9!). I'm fairly new to Javascript, especially hunting down IE problems with it.
Is there a function or method or something above that IE just won't recognize that I'll have to find an alternate way around?
IE needs
document.body.oncopy=copyCopyright
added to your onload event. (body doesn’t exist until loaded)
In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?
For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.
function copyIntoClipboard(text) {
var flashId = 'flashId-HKxmj5';
/* Replace this with your clipboard.swf location */
var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';
if(!document.getElementById(flashId)) {
var div = document.createElement('div');
div.id = flashId;
document.body.appendChild(div);
}
document.getElementById(flashId).innerHTML = '';
var content = '<embed src="' +
clipboardSWF +
'" FlashVars="clipboard=' + encodeURIComponent(text) +
'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashId).innerHTML = content;
}
The only disadvantage is that this requires Flash to be enabled.
The source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is its Google cache)
There is now a way to easily do this in most modern browsers using
document.execCommand('copy');
This will copy currently selected text. You can select a textArea or input field using
document.getElementById('myText').select();
To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.
For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.
A full example:
function copier(){
document.getElementById('myText').select();
document.execCommand('copy');
}
<button onclick="copier()">Copy</button>
<textarea id="myText">Copy me PLEASE!!!</textarea>
Online spreadsheet applications hook Ctrl + C and Ctrl + V events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.
See also Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?.
It is summer 2015, and with so much turmoil surrounding Flash, here is how to avoid its use altogether.
clipboard.js is a nice utility that allows copying of text or html data to the clipboard. It's very easy to use, just include the .js and use something like this:
<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>
clipboard.js is also on GitHub.
As of 2017, you can do this:
function copyStringToClipboard (string) {
function handler (event){
event.clipboardData.setData('text/plain', string);
event.preventDefault();
document.removeEventListener('copy', handler, true);
}
document.addEventListener('copy', handler, true);
document.execCommand('copy');
}
And now to copy copyStringToClipboard('Hello, World!')
If you noticed the setData line, and wondered if you can set different data types, the answer is yes.
Firefox does allow you to store data in the clipboard, but due to security implications it is disabled by default. See how to enable it in "Granting JavaScript access to the clipboard" in the Mozilla Firefox knowledge base.
The solution offered by amdfan is the best if you are having a lot of users and configuring their browser isn't an option. Though you could test if the clipboard is available and provide a link for changing the settings, if the users are tech savvy. The JavaScript editor TinyMCE follows this approach.
The copyIntoClipboard() function works for Flash 9, but it appears to be broken by the release of Flash player 10. Here's a solution that does work with the new flash player:
http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/
It's a complex solution, but it does work.
I have to say that none of these solutions really work. I have tried the clipboard solution from the accepted answer, and it does not work with Flash Player 10. I have also tried ZeroClipboard, and I was very happy with it for awhile.
I'm currently using it on my own site (http://www.blogtrog.com), but I've been noticing weird bugs with it. The way ZeroClipboard works is that it puts an invisible flash object over the top of an element on your page. I've found that if my element moves (like when the user resizes the window and i have things right aligned), the ZeroClipboard flash object gets out of whack and is no longer covering the object. I suspect it's probably still sitting where it was originally. They have code that's supposed to stop that, or restick it to the element, but it doesn't seem to work well.
So... in the next version of BlogTrog, I guess I'll follow suit with all the other code highlighters I've seen out in the wild and remove my Copy to Clipboard button. :-(
(I noticed that dp.syntaxhiglighter's Copy to Clipboard is broken now also.)
Check this link:
Granting JavaScript access to the clipboard
Like everybody said, for security reasons, it is by default disabled. The page above shows the instructions of how to enable it (by editing about:config in Firefox or the user.js file).
Fortunately, there is a plugin called "AllowClipboardHelper" which makes things easier with only a few clicks. however you still need to instruct your website's visitors on how to enable the access in Firefox.
Use the modern document.execCommand("copy") and jQuery. See this Stack Overflow answer.
var ClipboardHelper = { // As Object
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}
};
How to call it:
ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());
// jQuery document
;(function ( $, window, document, undefined ) {
var ClipboardHelper = {
copyElement: function ($element)
{
this.copyText($element.text())
},
copyText:function(text) // Linebreaks with \n
{
var $tempInput = $("<textarea>");
$("body").append($tempInput);
//todo prepare Text: remove double whitespaces, trim
$tempInput.val(text).select();
document.execCommand("copy");
$tempInput.remove();
}
};
$(document).ready(function()
{
var $body = $('body');
$body.on('click', '*[data-copy-text-to-clipboard]', function(event)
{
var $btn = $(this);
var text = $btn.attr('data-copy-text-to-clipboard');
ClipboardHelper.copyText(text);
});
$body.on('click', '.js-copy-element-to-clipboard', function(event)
{
ClipboardHelper.copyElement($(this));
});
});
})( jQuery, window, document );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span data-copy-text-to-clipboard=
"Hello
World">
Copy Text
</span>
<br><br>
<span class="js-copy-element-to-clipboard">
Hello
World
Element
</span>
I've used GitHub's Clippy for my needs and is a simple Flash-based button. It works just fine if one doesn't need styling and is pleased with inserting what to paste on the server-side beforehand.
http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp works with Flash 10 and all Flash enabled browsers.
Also ZeroClipboard has been updated to avoid the bug mentioned about page scrolling causing the Flash movie to no longer be in the correct place.
Since that method "Requires" the user to click a button to copy this is a convenience to the user and nothing nefarious is occurring.
A slight improvement on the Flash solution is to detect for Flash 10 using swfobject:
http://code.google.com/p/swfobject/
And then if it shows as Flash 10, try loading a Shockwave object using JavaScript. Shockwave can read/write to the clipboard (in all versions) as well using the copyToClipboard() command in Lingo.
Try creating a memory global variable storing the selection. Then the other function can access the variable and do a paste. For example,
var memory = ''; // Outside the functions but within the script tag.
function moz_stringCopy(DOMEle, firstPos, secondPos) {
var copiedString = DOMEle.value.slice(firstPos, secondPos);
memory = copiedString;
}
function moz_stringPaste(DOMEle, newpos) {
DOMEle.value = DOMEle.value.slice(0, newpos) + memory + DOMEle.value.slice(newpos);
}
If you support Flash, you can use https://everyplay.com/assets/clipboard.swf and use the flashvars text to set the text.
https://everyplay.com/assets/clipboard.swf?text=It%20Works
That’s the one I use to copy and you can set as extra if it doesn't support these options. You can use:
For Internet Explorer:
window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)
You can use the DataFormat's Text and URL to getData and setData.
And to delete data:
You can use the DataFormat's File, HTML, Image, Text and URL. PS: You need to use window.clipboardData.clearData(DataFormat);.
And for other that’s not support window.clipboardData and swf Flash files you can also use Control + C button on your keyboard for Windows and for Mac its Command + C.
From addon code:
For how to do it from Chrome code, you can use the nsIClipboardHelper interface as described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard
Use document.execCommand('copy'). It is supported in the latest versions of Chrome, Firefox, Edge, and Safari.
function copyText(text){
function selectElementText(element) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(element);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
var element = document.createElement('DIV');
element.textContent = text;
document.body.appendChild(element);
selectElementText(element);
document.execCommand('copy');
element.remove();
}
var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
copyText(txt.value);
})
<input id="txt" value="Hello World!" />
<button id="btn">Copy To Clipboard</button>
Clipboard API is designed to supersede document.execCommand. Safari is still working on support, so you should provide a fallback until the specification settles and Safari finishes implementation.
const permalink = document.querySelector('[rel="bookmark"]');
const output = document.querySelector('output');
permalink.onclick = evt => {
evt.preventDefault();
window.navigator.clipboard.writeText(
permalink.href
).then(() => {
output.textContent = 'Copied';
}, () => {
output.textContent = 'Not copied';
});
};
Permalink
<output></output>
For security reasons clipboard Permissions may be necessary to read and write from the clipboard. If the snippet doesn't work on Stack Overflow give it a shot on localhost or an otherwise trusted domain.
Building off the excellent answer from David from Studio.201, this works in Safari, Firefox, and Chrome. It also ensures no flashing could occur from the textarea by placing it off-screen.
// ================================================================================
// ClipboardClass
// ================================================================================
var ClipboardClass = (function() {
function copyText(text) {
// Create temp element off-screen to hold text.
var tempElem = $('<textarea style="position: absolute; top: -8888px; left: -8888px">');
$("body").append(tempElem);
tempElem.val(text).select();
document.execCommand("copy");
tempElem.remove();
}
// ============================================================================
// Class API
// ============================================================================
return {
copyText: copyText
};
})();