I found many solutions for copying to the clipboard, but they all either with flash, or for websites side. I'm looking for method copy to clipboard automatically, without flas开发者_JAVA百科h and for user side, it's for userscripts and of course cross-browser.
Without flash, it's simply not possible in most browsers. The user's clipboard is a security-relevant resource since it could contain things like passwords or credit card numbers. Thus, browsers rightly don't allow Javascript access to it (some allow it with a warning shown that the user has confirm, or with signed Javascript code, but none of that is cross-browser).
I had tryed the flash solution and I don't liked too. Too complex and too slow. What I did was to create a textarea, put the data into that and use the browser "CTRL + C" behavior.
The jQuery javascript part:
// catch the "ctrl" combination keydown
$.ctrl = function(key, callback, args) {
$(document).keydown(function(e) {
if(!args) args=[]; // IE barks when args is null
if(e.keyCode == key && e.ctrlKey) {
callback.apply(this, args);
return false;
}
});
};
// put your data on the textarea and select all
var performCopy = function() {
var textArea = $("#textArea1");
textArea.text('PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.');
textArea[0].focus();
textArea[0].select();
};
// bind CTRL + C
$.ctrl('C'.charCodeAt(0), performCopy);
The HTML part:
<textarea id="textArea1"></textarea>
Now, put what do you want to copy in 'PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.' area. Works fine for me me. You just have to make one CTRL+C combination. The only drawback is that you are going to have an ugly textarea displayed in you site. If you use the style="display:none" the copy solution will not work.
clipboard.js has just been released to copy to clipboard without the need of Flash
See it in action here > http://zenorocha.github.io/clipboard.js/#example-action
It's finally here! (As long as you don't support Safari or IE8... -_- )
You can now actually handle clipboard actions without Flash. Here's the relevant documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en
https://msdn.microsoft.com/en-us/library/hh801227%28v=vs.85%29.aspx#copy
While waiting impatiently for Xbrowser support of the Clipboard API...
This will work beautifully in Chrome, Firefox, Edge, IE
IE will only prompt the user once to access the Clipboard.
Safari (5.1 at the time of writing) does not support execCommand
for copy/cut
/**
* CLIPBOARD
* https://stackoverflow.com/a/33337109/383904
*/
const clip = e => {
e.preventDefault();
const cont = e.target.innerHTML;
const area = document.createElement("textarea");
area.value = e.target.innerHTML; // or use .textContent
document.body.appendChild(area);
area.select();
if(document.execCommand('copy')) console.log("Copied to clipboard");
else prompt("Copy to clipboard:\nSelect, Cmd+C, Enter", cont); // Saf, Other
area.remove();
};
[...document.querySelectorAll(".clip")].forEach(el =>
el.addEventListener("click", clip)
);
<a class="clip" href="#!">Click an item to copy</a><br>
<a class="clip" href="#!"><i>Lorem</i></a><br>
<a class="clip" href="#!"><b>IPSUM</b></a><br>
<textarea placeholder="Paste here to test"></textarea>
All browsers (except Firefox which is able to only handle mime type "plain/text"
as far as I've tested) have not implemented the Clipboard API. I.e, trying to read the clipboard event in Chrome using
var clipboardEvent = new ClipboardEvent("copy", {
dataType: "plain/text",
data: "Text to be sent to clipboard"
});
throws: Uncaught TypeError: Illegal constructor
The best resource of the unbelievable mess that's happening among browsers and the Clipboard can be seen here (caniuse.com) (→ Follow the comments under "Notes").
MDN says that basic support is "(YES)" for all browsers which is inaccurate cause one would expect at least the API to work, at all.
You can use a clipboard local to the HTML page. This allows you to copy/cut/paste content WITHIN the HTML page, but not from/to third party applications or between two HTML pages.
This is how you can write a custom function to do this (tested in chrome and firefox):
Here is the FIDDLE that demonstrates how you can do this.
I will also paste the fiddle here for reference.
HTML
<p id="textToCopy">This is the text to be copied</p>
<input id="inputNode" type="text" placeholder="Copied text will be pasted here" /> <br/>
<a href="#" onclick="cb.copy()">copy</a>
<a href="#" onclick="cb.cut()">cut</a>
<a href="#" onclick="cb.paste()">paste</a>
JS
function Clipboard() {
/* Here we're hardcoding the range of the copy
and paste. Change to achieve desire behavior. You can
get the range for a user selection using
window.getSelection or document.selection on Opera*/
this.oRange = document.createRange();
var textNode = document.getElementById("textToCopy");
var inputNode = document.getElementById("inputNode");
this.oRange.setStart(textNode,0);
this.oRange.setEndAfter(textNode);
/* --------------------------------- */
}
Clipboard.prototype.copy = function() {
this.oFragment= this.oRange.cloneContents();
};
Clipboard.prototype.cut = function() {
this.oFragment = this.oRange.extractContents();
};
Clipboard.prototype.paste = function() {
var cloneFragment=this.oFragment.cloneNode(true)
inputNode.value = cloneFragment.textContent;
};
window.cb = new Clipboard();
document.execCommand('copy')
will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:
var textNode = document.querySelector('p').firstChild
var range = document.createRange()
var sel = window.getSelection()
range.setStart(textNode, 0)
range.setEndAfter(textNode)
sel.removeAllRanges()
sel.addRange(range)
document.execCommand('copy')
There is not way around, you have to use flash. There is a JQuery plugin called jquery.copy that provided cross browser copy and paste by using a flash (swf) file. This is similar to how the syntax highlighter on my blog works.
Once you reference the jquery.copy.js file all you need to do to push data into the clipboard is run the following:
$.copy("some text to copy");
Nice and easy ;)
精彩评论