复制到剪贴板,无需 Flash

发布于 2024-11-16 00:52:13 字数 89 浏览 0 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

平安喜乐 2024-11-23 00:52:13

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

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

月棠 2024-11-23 00:52:13

我尝试过 flash 解决方案,但我也不喜欢。太复杂而且太慢。我所做的是创建一个文本区域,将数据放入其中并使用浏览器“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 部分:

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

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.

薔薇婲 2024-11-23 00:52:13

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

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

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

橘和柠 2024-11-23 00:52:13

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

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

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

https://developers.google.com/web/updates/2015/ 04/剪切和复制命令?hl=zh-CN

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

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

千秋岁 2024-11-23 00:52:13

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


This will work beautifully in **Chrome, Firefox, Edge, IE**

IE只会提示用户一次访问剪贴板。
Safari(撰写本文时为 5.1)不支持 execCommand 进行复制/剪切

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

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

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

Uncaught TypeError: Illegal constructor

可以看到浏览器和剪贴板之间发生的令人难以置信的混乱的最佳资源< a href="http://caniuse.com/#feat=clipboard" rel="nofollow noreferrer">此处 (caniuse.com) (→ 按照下面的评论进行操作“注释”)。
MDN 表示对所有浏览器的基本支持是“(是)”,这是不准确的,因为人们会期望至少 API 能够工作。

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 = (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>

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.

时光清浅 2024-11-23 00:52:13

您可以使用 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();

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();
凉栀 2024-11-23 00:52:13

document.execCommand('copy') 将执行您想要的操作。但是这个线程中没有直接可用的示例,所以这里是:

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

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')
水中月 2024-11-23 00:52:13

没办法,只能用闪光灯。有一个名为 jquery.copy 的 JQuery 插件,它提供使用 Flash (swf) 进行跨浏览器复制和粘贴的功能文件。这类似于我博客上的语法荧光笔的工作原理。

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

$.copy("some text to 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 ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文