Copy to clipboard with jQuery/js in Chrome - javascript

I know this kind of question has been asked here for many times, including: How do I copy to the clipboard in JavaScript? or How to copy text to the client's clipboard using jQuery?, I'm narrowing the scope:
Condition:
works fine in Google Chrome (would be nice if cross-browser, but not necessary)
with no flash
Is there such a solution or workaround?

You can use either document.execCommand('copy') or addEventListener('copy'), or a combination of both.
1. copy selection on custom event
If you want to trigger a copy on some other event than ctrl-c or right click copy, you use document.execCommand('copy'). It'll copy what's currently selected. Like this, on mouseup for example:
elem.onmouseup = function(){
document.execCommand('copy');
}
EDIT:
document.execCommand('copy') is supported only by Chrome 42, IE9 and Opera 29, but will be supported by firefox 41 (scheduled for september 2015). Note that IE will normally asks for permission to access the clipboard.
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
2. copy custom content on copy triggered by user
Or, you can use addEventListener('copy'), this will interfere with copy event and you can put the content you want there. This suppose user triggers copy.
EDIT:
On Chrome, Firefox and Safari the event has the clipboardData object with setData method. On IE, the clipboardData object is a window property. So this can work on all major browsers provided you validate where is clipboardData.
elem2.addEventListener('copy', function (e) {
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', 'custom content');
} else if (window.clipboardData) {
window.clipboardData.setData('Text', 'custom content');
}
});
https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/clipboardData
https://msdn.microsoft.com/en-us/library/ms535220(v=vs.85).aspx
3. a bit of both
Using a combination, you can copy custom content on wanted events. So the first event triggers execCommand, then the listener interferes. For example, put custom content on click on a div.
elem3.onclick = function () {
document.execCommand('copy');
}
elem3.addEventListener('copy', function (e) {
e.preventDefault();
if (e.clipboardData) {
e.clipboardData.setData('text/plain', 'custom content from click');
} else if (window.clipboardData) {
window.clipboardData.setData('Text', 'custom content from click');
}
});
Using this last one supposes that both approach are supported, as of July 2015, it works only on Chrome 43 (maybe 42 I couldn't test) and IE at least 9 and 10. With Firefox 41 supporting execcommand('copy'), it should work as well.
Note that for most of these methods and properties are declared as either experimental (or even deprecated for IE), so it's to be used carefully, but it looks like it's more and more supported.
Fiddle with all examples: https://jsfiddle.net/jsLfnnvy/12/

I just find another amazing repo on Github.
Modern copy to clipboard. No Flash. Just 3kb gzipped
https://github.com/zenorocha/clipboard.js
Browser Support:

If you don't mind IE/Safari, you can use following (new) API:
var promise = navigator.clipboard.writeText(newClipText)
Read the docs here

Variable string can copy to clipboard using below js code.
var text = 'text to copy';
var copyFrom = $('<textarea/>');
copyFrom.css({
position: "absolute",
left: "-1000px",
top: "-1000px",
});
copyFrom.text(text);
$('body').append(copyFrom);
copyFrom.select();
document.execCommand('copy');

Actually for those figuring this out i got it to work in chrome based on #JulianGregoire s answer.
I rewrote the code to make it a bit better in my opinion:
el.onclick = function () {
var copy = function (e) {
e.preventDefault();
console.log('copy');
var text = "blabla"
if (e.clipboardData) {
e.clipboardData.setData('text/plain', text);
} else if (window.clipboardData) {
window.clipboardData.setData('Text', text);
}
}
window.addEventListener('copy', copy);
document.execCommand('copy');
window.removeEventListener('copy', copy);
}

Beware: I tried the exact same script of Julien Grégoire, however it wasn't triggering the oncopy event listener. The reason, I had user-select CSS for the body-tag.
So make sure you remove it, or set it to initial on the element the event listener is attached to.
Example: https://jsfiddle.net/faimmedia/jsLfnnvy/80/

If you're using knockout, like me (for some reason I still am), you'll want to take a look at this question/answer:
How to make KnokoutJS and ClipboardJS work together?

function copyToClipboard(s) {
if (window.clipboardData && clipboardData.setData) {
clipboardData.setData('text', s);
}
}
Then call the function with the text and that should work.

Related

Get Pasted Image from Clipboard Firefox

I'm trying to allow the user to paste an image into a div. The problem is that I need it work in Firefox.
From what I've read, Firefox since version 13 (I think) doesn't allow JavaScript access to the clipboard, and event.clipboard doesn't exist in it. I know it can be done because Gmail and Yahoo alow it even in Firefox.
I just want it to work in anyway posible, be with jQuery, JavaScript, HTML5, it doesn't matter as long as it works in the latest Firefox. (No Flash though).
I used the code from this question for my cross-browser paste implementation.. it works in all browsers I have tested (scroll down for the actual solution/code). It should be noted that event.clipboardData expires immediately after the paste event has completed execution.
I went ahead and quadruple checked that this does work in Firefox version 19 (I don't have 13 available, but it sounds like this question was about degradation of a feature in newer versions).
Below is the answer, quoted from Nico Burns:
Solution
Tested in IE6+, FF 3.5+, recent-ish versions of Opera, Chrome, Safari.
function handlepaste (elem, e) {
var savedcontent = elem.innerHTML;
if (e && e.clipboardData && e.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
if (/text\/html/.test(e.clipboardData.types)) {
elem.innerHTML = e.clipboardData.getData('text/html');
}
else if (/text\/plain/.test(e.clipboardData.types)) {
elem.innerHTML = e.clipboardData.getData('text/plain');
}
else {
elem.innerHTML = "";
}
waitforpastedata(elem, savedcontent);
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
}
else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
elem.innerHTML = "";
waitforpastedata(elem, savedcontent);
return true;
}
}
function waitforpastedata (elem, savedcontent) {
if (elem.childNodes && elem.childNodes.length > 0) {
processpaste(elem, savedcontent);
}
else {
that = {
e: elem,
s: savedcontent
}
that.callself = function () {
waitforpastedata(that.e, that.s)
}
setTimeout(that.callself,20);
}
}
function processpaste (elem, savedcontent) {
pasteddata = elem.innerHTML;
//^^Alternatively loop through dom (elem.childNodes or elem.getElementsByTagName) here
elem.innerHTML = savedcontent;
// Do whatever with gathered data;
alert(pasteddata);
}
<div id='div' contenteditable='true' onpaste='handlepaste(this, event)'>Paste</div>
Explanation
The onpaste event has the handlepaste function attached to it, and passed two arguments: this (i.e. a reference to the element that the event is attached to) and event which is the event object.
The handlepaste function:
The first line simply saves the content of the editable div to a variable so it can be restored again at the end.
The if checks whether the browser is an webkit browser (chrome or safari), and if it is it sets contents of the editable div to the data being pasted. It then cancels the event to prevent webkit pasting anything twice. This is because webkit is awkward, and won't paste anything if you simply clear the div.
If it is not a webkit browser then it simply clears the editable div.
It then calls the waitforpastedata function
The waitforpastedata function:
This is necessary because the pasted data doesn't appear straight away, so if you just called processpaste straight away then it wouldn't have any data to process.
What it does is check if the editable div has any content, if it does then calls processpaste, otherwise it sets a timer to call itself and check again in 20 milliseconds.
The processpaste function:
This function saved the innerHTML of the editable div (which is now the pasted data) to a variable, restores the innerHTML of the editable div back to its original value, and the alert the pasted data. Obviously in a real usage scenario you would probably want to something other than just alert data, you can do whatever you like with it from here.
You will probably also want to run the pasted data through some kind of data sanitising process. This can be done either while it is still in the editable div, or on the extracted string.
In a real sitution you would probably want to save the selection before, and restore it afterwards (Set cursor position on contentEditable <div>). You could then insert the pasted data at the position the cursor was in when the user initiated the paste action.
P.S. The combination of this code, IE <= 8 and jsfiddle doesn't seem to work, but it does work in ie <= 8 in a non-jsfiddle environment.

Is there a cross browser way to prevent cut, copy and paste on a website in plain Javascript?

I found an answer, but it was for JQuery. Here is the link:
http://jquerybyexample.blogspot.com/2010/12/disable-cut-copy-and-paste-function-for.html
: I want something in plain Javascript which work on chrome, latest firefox, safari, and IE 8 and 9.
Update
Due to all the negative comments saying that this is a bad idea for an internet site I can only say "I agree". Please note that this is for an "intranet" application where cut, copy, and paste need to be overidden as the default browser behaviour for cut copy and paste needs to be customized to handle embedded tags in a rich text area
of course it is not appropriate to do stuff like this, but that was not #Zubairs question, so i think voting down is not correct here, as he made his point clear.
now to the question: if jQuery can do it, native javascript can do it of course too.
you must prevent the cut, copy and paste events:
document.body.oncopy = function() { return false; }
document.body.oncut = function() { return false; }
document.body.onpaste = function() { return false; }
this prevents the right-click-context-menu, this is not needed if you use the 3 other event-handlers but just to let you know ;-)
document.body.oncontextmenu = function() { return false; }
IMPORTANT: the body must be loaded (of course), document.body because IE needs it (document.oncopy will only work in chrome/firefox/safari)
a good way
var D=document.getElementById('b4');
if(D.addEventListener){
D.addEventListener('paste',function(e){false;e.preventDefault();},false);}
else{
D.attachEvent('onpaste',function(){return false;});}
warning : code must be under html target/s ,
just before the close body tag for example
Edit: adding this to a body tag seems to work on all of my test browsers including the Opera, Chrome, Seamonkey (so I assume Firefox) and IE9
<body oncopy='return false' oncut='return false' onpaste='return false'>
you can put them in other tags if you want to allow some functions in some places and not in others
You can catch a [Ctrl]+[C] keypress:
addEventListener("keydown", function(e){
evt = (e) ? e : window.event; // Some cross-browser compatibility.
if(evt.ctrlKey && evt.which == 67){ // [x] == 88; [c] == 67; [v] == 86;
console.log("Ctrl+C pressed!");
evt.preventDefault(); // Cancel the copy-ing function for the client.
// Manual Copy / Paste / Cut code here.
}
});​
Working snippet
oncopy="return false" oncut="return false" onpaste="return false"
This code will be prevent cut, copy and paste of a website.
Working Snippet

Self-closing popups in IE -- how to get proper onBlur behavior?

I want a transient window to close itself when the user clicks away from it. This works for Firefox:
var w = window.open(...);
dojo.connect(w, "onblur", w, "close");
but it doesn't seem to work in Internet Explorer. Some other sites made reference to an IE-specific "onfocusout" event, but I couldn't find a coherent working example of what I need.
What does Stack Overflow say about the best way to get IE browser windows to close when they lose focus?
I'm using Dojo so if there's some shortcut in that library, information would be welcome. Otherwise standard IE calls will be the best answer.
I figured out the alternative in IE.
This:
that.previewWindowAction = function () {
var pw =
window.open(this.link, "preview",
"height=600,width=1024,resizable=yes,"
+ "scrollbars=yes,dependent=yes");
dojo.connect(pw, "onblur", pw, "close");
};
should be written like this to work in IE:
that.previewWindowAction = function () {
var pw =
window.open(this.link, "preview",
"height=600,width=1024,resizable=yes,"
+ "scrollbars=yes,dependent=yes");
if (dojo.isIE) {
dojo.connect
(pw.document,
"onfocusin",
null,
function () {
var active = pw.document.activeElement;
dojo.connect
(pw.document,
"onfocusout",
null,
function () {
if (active != pw.document.activeElement) {
active = pw.document.activeElement;
} else {
window.open("", "preview").close();
}
});
});
}
else {
dojo.connect(pw, "onblur", pw, "close");
}
};
The reasons?
In IE, window objects do not respond to blur events. Therefore we must use the proprietary onfocusout event.
In IE, onfocusout is sent by most HTML elements, so we must add some logic to determine which onfocusout is the one caused by the window losing focus. In onfocusout, the activeElement attribute of the document is always different from the previous value -- except when the window itself loses focus. This is the cue to close the window.
In IE, documents in a new window send an onfocusout when the window is first created. Therefore, we must only add the onfocusout handler after it has been brought into focus.
In IE, window.open does not appear to reliably return a window handle when new windows are created. Therefore we must look up the window by name in order to close it.
Try:
document.onfocusout = window.close();
You might try this as part of an IE-specific code block:
w.onblur = function() { w.close();};

Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?

I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function
window.clipboardData.getData("Text")
Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?
Safari supports reading the clipboard during onpaste events:
Information
You want to do something like:
someDomNode.onpaste = function(e) {
var paste = e.clipboardData && e.clipboardData.getData ?
e.clipboardData.getData('text/plain') : // Standard
window.clipboardData && window.clipboardData.getData ?
window.clipboardData.getData('Text') : // MS
false;
if(paste) {
// ...
}
};
Online Spreadsheets hook Ctrl+C, Ctrl+V events and transfer focus to a hidden TextArea control and either set it contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.
NO. And if you do find a hack (e.g. old version of flash) do not depend on it.
Can I ask why you want to read from the clipboard? If the user wants to pass along the clipboard contents, all they need to do is paste.
I believe people use a hidden Flash element to read the clipboard data from the browsers you mentioned.
Using #agsamek suggestion I created a little test snipped and got it to work. In my case I need to wait after a fresh pageload for pasted input, so I focus on an out-of-view textarea and read the text from there.
You could extend this to listen to specific keys (paste combination) and then focus on the hidden field. There would definitely more work to be done as I think you need to re-focus then on the last focused element and paste content there.
For my use-case though this was enough to make it work in latest Chrome and Firefox. Suggestions welcome.
https://jsfiddle.net/wuestkamp/91dxjv7s/11/
$(function () {
$('body').prepend('<input type="text" id="hidden_textbox" style="position: absolute; width:0px; height: 0px; top: -100px; left: -100px">');
var $hiddenTextbox = $('#hidden_textbox');
$hiddenTextbox.focus();
$(document).on('paste', function () {
setTimeout(function () {
var val = $hiddenTextbox.val();
console.log('pasted: ' + val);
}, 50);
});
});

Copy / Put text on the clipboard with FireFox, Safari and Chrome

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
};
})();

Categories

Resources