Javascript 无需 Flash 即可复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6355300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:23:31  来源:igfitidea点击:

Copy to clipboard without Flash

javascriptjqueryclipboard

提问by Black_Sun

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 flash and for user side, it's for userscripts and of course cross-browser.

我找到了许多复制到剪贴板的解决方案,但它们都带有 Flash,或用于网站端。我正在寻找自动复制到剪贴板的方法,无需闪存,对于用户端,它适用于用户脚本,当然也适用于跨浏览器。

回答by Michael Borgwardt

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).

没有 flash,在大多数浏览器中根本不可能。用户的剪贴板是与安全相关的资源,因为它可能包含密码或信用卡号等内容。因此,浏览器不允许 Javascript 访问它是正确的(有些允许它显示用户已确认的警告或签名的 Javascript 代码,但这些都不是跨浏览器的)。

回答by Julio Saito

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.

我曾尝试过闪存解决方案,但我也不喜欢。太复杂太慢了。我所做的是创建一个文本区域,将数据放入其中并使用浏览器“CTRL + C”行为。

The jQuery javascript part:

jQuery javascript 部分:

// 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>

HTML部分:
<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.

现在,将您要复制的内容放入“将文本复制到此处”。可以是一个函数。区域。对我来说很好用。您只需要进行一个 CTRL+C 组合。唯一的缺点是您将在您的站点中显示一个丑陋的文本区域。如果您使用 style="display:none" 复制解决方案将不起作用。

回答by malditojavi

clipboard.jshas just been released to copy to clipboard without the need of Flash

clipboard.js刚刚发布,无需 Flash 即可复制到剪贴板

See it in action here > http://zenorocha.github.io/clipboard.js/#example-action

在这里查看它的实际效果 > http://zenorocha.github.io/clipboard.js/#example-action

回答by Hovis Biddle

It's finally here!(As long as you don't support Safari or IE8... -_- )

终于来了!(只要你不支持 Safari 或 IE8... -_- )

You can now actually handle clipboard actions without Flash. Here's the relevant documentation:

您现在可以在没有 Flash 的情况下实际处理剪贴板操作。这是相关文档:

https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

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://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

https://msdn.microsoft.com/en-us/library/hh801227%28v=vs.85%29.aspx#copy

回答by Roko C. Buljan

While waiting impatientlyfor Xbrowser support of the Clipboard API...

不耐烦地等待剪贴板 API 的Xbrowser 支持时......



这将在 Chrome, Firefox, Edge, IEChrome、火狐、Edge、IE

IEwill only prompt the user once to access the Clipboard.
Safari(5.1 at the time of writing) does not support execCommandfor copy/cut

IE只会提示用户访问剪贴板一次。
Safari浏览器(5.1在写作的时间)不支持execCommandcopy/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 implementedthe Clipboard API. I.e, trying to read the clipboard event in Chrome using

所有的浏览器(Firefox的除外,它能够只处理MIME类型"plain/text",据我测试过)都没有实现剪贴板API。即,尝试使用 Chrome 读取剪贴板事件

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 messthat'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.

浏览器和剪贴板之间发生的令人难以置信的混乱的最佳资源可以在这里看到(caniuse.com)(→ 按照“注释”下的评论)。
MDN 表示对所有浏览器的基本支持都是“(是)”,这是不准确的,因为人们期望至少 API 能够正常工作。

回答by mrBorna

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.

您可以使用 HTML 页面的本地剪贴板。这允许您在 HTML 页面内复制/剪切/粘贴内容,但不能从/向第三方应用程序或在两个 HTML 页面之间复制/剪切/粘贴内容。

This is how you can write a custom function to do this (tested in chrome and firefox):

这是您如何编写自定义函数来执行此操作(在 chrome 和 firefox 中测试):

Here is the FIDDLEthat demonstrates how you can do this.

这是演示如何执行此操作的FIDDLE

I will also paste the fiddle here for reference.

我也会在这里粘贴小提琴以供参考。



HTML

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

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

回答by odinho - Velmont

document.execCommand('copy')will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:

document.execCommand('copy')会做你想做的。但是在这个线程中没有没有cruft的直接可用的例子,所以这里是:

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')

回答by Talha Ahmed Khan

There is not way around, you have to use flash. There is a JQuery plugin called jquery.copythat provided cross browser copy and paste by using a flash (swf) file. This is similar to how the syntax highlighter on my blog works.

没有办法,你必须使用闪光灯。有一个名为jquery.copy的 JQuery 插件,它通过使用 flash (swf) 文件提供跨浏览器复制和粘贴。这类似于我博客上的语法高亮器的工作方式。

Once you reference the jquery.copy.js file all you need to do to push data into the clipboard is run the following:

引用 jquery.copy.js 文件后,将数据推送到剪贴板所需要做的就是运行以下命令:

$.copy("some text to copy");

Nice and easy ;)

好,易于 ;)