不使用Flash复制到剪贴板

Copy to clipboard without Flash

本文关键字:剪贴板 复制 Flash      更新时间:2023-09-26

我发现了许多复制到剪贴板的解决方案,但它们都是用flash或网站端的。我正在寻找自动复制到剪贴板的方法,没有flash,对于用户端,它是为用户脚本,当然还有跨浏览器。

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

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

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

HTML部分:
<textarea id="textArea1"></textarea>

现在,把你想复制的内容放在"把文本放在这里复制"中。可以是一个函数地区对我来说很好。你只需要做一个CTRL+C组合。唯一的缺点是,你会在你的网站上显示一个丑陋的文本区域。如果使用style="display:none",复制解决方案将不起作用。

clipboard.js刚刚发布,可以在不需要Flash 的情况下复制到剪贴板

在此处查看它的实际操作>http://zenorocha.github.io/clipboard.js/#example-动作

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

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

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

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


这将在**Chrome、Firefox、Edge、IE中完美运行**

IE将只提示用户访问剪贴板一次
Safari(撰写本文时为5.1)不支持execCommand用于copy/cut

/**
 * CLIPBOARD
 * https://stackoverflow.com/a/33337109/383904
 */
const clip = (val) => {  
  const area = document.createElement("textarea");
  area.value = val;
  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", (evt) => {
    evt.preventDefault();
    clip(evt.currentTarget.textContent);
  });
});
<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>

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

var clipboardEvent = new ClipboardEvent("copy", {
  dataType: "plain/text",
  data: "Text to be sent to clipboard"
});

throws:未捕获类型错误:非法构造函数

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

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

这就是你如何编写一个自定义函数来做到这一点(在chrome和firefox中测试):

以下是FIDDLE,它演示了如何做到这一点

我也会把小提琴粘贴在这里作为参考。


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')将执行您想要的操作。但在这个线程中,没有没有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')

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

引用jquery.copy.js文件后,将数据推入剪贴板所需的操作如下:

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

漂亮又简单;)