如何在 JavaScript 中复制到剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello 如何访问用户的剪贴板?< /em>
How do I copy text to the clipboard (multi-browser)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何将文本复制到剪贴板(多浏览器)?
相关:Trello 如何访问用户的剪贴板?< /em>
How do I copy text to the clipboard (multi-browser)?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(27)
概述
用于复制到剪贴板的主要浏览器 API 包括三个:
异步剪贴板API
[navigator.clipboard.writeText]
document.execCommand('copy')
(已弃用)Overview
There are three primary browser APIs for copying to the clipboard:
Async Clipboard API
[navigator.clipboard.writeText]
document.execCommand('copy')
(deprecated) ????Overriding the copy event
General development notes
Don't expect clipboard related commands to work whilst you are testing code in the console. Generally, the page is required to be active (Async Clipboard API) or requires user interaction (e.g. a user click) to allow (
document.execCommand('copy')
) to access the clipboard see below for more detail.IMPORTANT (noted here 2020/02/20)
Note that since this post was originally written deprecation of permissions in cross-origin IFRAMEs and other IFRAME "sandboxing" prevents the embedded demos "Run code snippet" buttons and "codepen.io example" from working in some browsers (including Chrome and Microsoft Edge).
To develop create your own web page, serve that page over an HTTPS connection to test and develop against.
Here is a test/demo page which demonstrates the code working:
https://deanmarktaylor.github.io/clipboard-test/
Async + Fallback
Due to the level of browser support for the new Async Clipboard API, you will likely want to fall back to the
document.execCommand('copy')
method to get good browser coverage.Here is a simple example (may not work embedded in this site, read "important" note above):
(codepen.io example may not work, read "important" note above)
Note that this snippet is not working well in Stack Overflow's embedded preview you can try it here: https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors=1011
Async Clipboard API
Note that there is an ability to "request permission" and test for access to the clipboard via the permissions API in Chrome 66.
document.execCommand('copy')
The rest of this post goes into the nuances and detail of the
document.execCommand('copy')
API.Browser Support
The JavaScript(deprecated) ????document.execCommand('copy')
support has grown, see the links below for browser updates:Simple Example
(may not work embedded in this site, read "important" note above)
Complex Example: Copy to clipboard without displaying input
The above simple example works great if there is a
textarea
orinput
element visible on the screen.In some cases, you might wish to copy text to the clipboard without displaying an
input
/textarea
element. This is one example of a way to work around this (basically insert an element, copy to clipboard, remove element):Tested with Google Chrome 44, Firefox 42.0a1, and Internet Explorer 11.0.8600.17814.
(may not work embedded in this site, read "important" note above)
Additional notes
Only works if the user takes an action
All
document.execCommand('copy')
calls must take place as a direct result of a user action, e.g. click event handler. This is a measure to prevent messing with the user's clipboard when they don't expect it.See the Google Developers post here for more info.
Clipboard API
Note the full Clipboard API draft specification can be found here:
https://w3c.github.io/clipboard-apis/
Is it supported?
document.queryCommandSupported('copy')
should returntrue
if the command "is supported by the browser".document.queryCommandEnabled('copy')
returntrue
if thedocument.execCommand('copy')
will succeed if called now. Checking to ensure the command was called from a user-initiated thread and other requirements are met.However, as an example of browser compatibility issues, Google Chrome from ~April to ~October 2015 only returned
true
fromdocument.queryCommandSupported('copy')
if the command was called from a user-initiated thread.Note compatibility detail below.
Browser Compatibility Detail
Whilst a simple call to
document.execCommand('copy')
wrapped in atry
/catch
block called as a result of a user click will get you the most compatibility use the following has some provisos:Any call to
document.execCommand
,document.queryCommandSupported
ordocument.queryCommandEnabled
should be wrapped in atry
/catch
block.Different browser implementations and browser versions throw differing types of exceptions when called instead of returning
false
.Different browser implementations are still in flux and the Clipboard API is still in draft, so remember to do your testing.
自动复制到剪贴板可能很危险,因此大多数浏览器(Internet Explorer 除外)都使其变得非常困难。就我个人而言,我使用以下简单的技巧:
向用户显示提示框,其中已选择要复制的文本。现在按 Ctrl+C 和 Enter(关闭该框)就足够了 - 瞧!
现在,剪贴板复制操作是安全的,因为用户手动执行此操作(但以非常简单的方式)。当然,它适用于所有浏览器。
Automatic copying to the clipboard may be dangerous, and therefore most browsers (except Internet Explorer) make it very difficult. Personally, I use the following simple trick:
The user is presented with the prompt box, where the text to be copied is already selected. Now it's enough to press Ctrl+C and Enter (to close the box) -- and voila!
Now the clipboard copy operation is safe, because the user does it manually (but in a pretty straightforward way). Of course, it works in all browsers.
以下方法适用于 Chrome、Firefox、Internet Explorer 和 Edge 以及最新版本的 Safari(2016 年 10 月发布的版本 10 中添加了复制支持)。
注意:您将看不到文本区域,因为它是在 Javascript 代码的同一同步调用中添加和删除的。
如果您自己实现此操作,需要注意一些事项:
下面的函数应该尽可能干净地处理以下所有问题。如果您发现任何问题或有任何改进建议,请发表评论。
https://jsfiddle.net/fx6a6n6x/
The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).
Note: you will not see the textarea, as it is added and removed within the same synchronous invocation of Javascript code.
Some things to watch out for if you are implementing this yourself:
The function below should handle all of the following issues as cleanly as possible. Please leave a comment if you find any problems or have any suggestions for improving it.
https://jsfiddle.net/fx6a6n6x/
这是我对此的看法...
@korayem:请注意,使用 html
input
字段不会考虑换行符\n
并将任何文本展平为单行。正如 @nikksan 在评论中提到的,使用
textarea
将解决该问题,如下所示:Here is my take on that one...
@korayem: Note that using html
input
field won't respect line breaks\n
and will flatten any text into a single line.As mentioned by @nikksan in the comments, using
textarea
will fix the problem as follows:从网页读取和修改剪贴板会引起安全和隐私问题。但是,在 Internet Explorer 中,可以做到这一点。我找到了这个示例片段:
Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:
如果您想要一个非常简单的解决方案(集成时间不到 5 分钟)并且开箱即用,那么 Clippy 是一些更复杂的解决方案的一个很好的替代方案。
它是由 GitHub 的联合创始人编写的。下面是 Flash 嵌入代码示例:
请记住将
#{text}
替换为您需要复制的文本,将#{bgcolor}
替换为颜色。If you want a really simple solution (takes less than 5 minutes to integrate) and looks good right out of the box, then Clippy is a nice alternative to some of the more complex solutions.
It was written by a cofounder of GitHub. Example Flash embed code below:
Remember to replace
#{text}
with the text you need copied, and#{bgcolor}
with a color.我最近写了一篇技术博客文章< /a> 就这个问题(我在 Lucidchart 工作,我们最近对剪贴板进行了彻底检查)。
将纯文本复制到剪贴板相对简单,假设您尝试在系统复制事件期间执行此操作(用户按 Ctrl+C 或使用浏览器的菜单)。
不在系统复制事件期间将文本放入剪贴板要困难得多。看起来这些其他答案中的一些参考了通过 Flash 来完成此操作的方法,这是唯一的跨浏览器方法(据我所知)。
除此之外,还有一些基于浏览器的选项。
这是 Internet Explorer 中最简单的,您可以随时从 JavaScript 通过以下方式访问 ClipboardData 对象:(
当您尝试在系统剪切、复制或粘贴事件之外执行此操作时,Internet Explorer 将提示用户授予 Web 应用程序剪贴板权限。)
在 Chrome 中,您可以创建一个 Chrome 扩展程序,该扩展程序将为您提供 剪贴板权限(这就是我们为 Lucidchart 所做的)。然后,对于安装了您的扩展的用户,您只需要自己触发系统事件:
看起来 Firefox 有 一些选项 允许用户授予某些网站访问剪贴板的权限,但我个人还没有尝试过这些。
I have recently written a technical blog post on this very problem (I work at Lucidchart and we recently did an overhaul on our clipboard).
Copying plain text to the clipboard is relatively simple, assuming you attempt to do it during a system copy event (user presses Ctrl+C or uses the browser's menu).
Putting text on the clipboard not during a system copy event is much more difficult. It looks like some of these other answers reference ways to do it via Flash, which is the only cross-browser way to do it (so far as I understand).
Other than that, there are some options on a browser-by-browser basis.
This is the most simple in Internet Explorer, where you can access the clipboardData object at anytime from JavaScript via:
(When you attempt to do this outside of a system cut, copy, or paste event, however, Internet Explorer will prompt the user to grant the web application clipboard permission.)
In Chrome, you can create a Chrome extension that will give you clipboard permissions (this is what we do for Lucidchart). Then for users with your extension installed you'll just need to fire the system event yourself:
It looks like Firefox has some options that allow users to grant permissions to certain sites to access the clipboard, but I haven't tried any of these personally.
我喜欢这一点:
如果用户不知道如何在操作系统中复制文本,那么他们很可能也不知道如何粘贴。所以只需让它自动选择,剩下的交给用户。
I like this one:
If a user doesn't know how to copy text in their OS, then it's likely they don't know how to paste either. So just have it automatically selected, leaving the rest to the user.
clipboard.js 是一个小型的非 Flash 实用程序,允许复制文本或 HTML数据到剪贴板。它非常容易使用,只需包含 .js 并使用如下内容即可:
clipboard.js 也在 GitHub< /a>.
clipboard.js is a small, non-Flash, 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:
clipboard.js is also on GitHub.
我非常成功地使用了它(没有 jQuery 或任何其他框架)。
警告
制表符会转换为空格(至少在 Chrome 中)。
I use this very successfully (without jQuery or any other framework).
Warning
Tabs are converted to spaces (at least in Chrome).
在 2018 年,你可以这样做:
它在我的 Angular 6+ 代码中使用如下:
如果我传入一个字符串,它会复制它。如果没有,它会复制页面的 URL。
还可以对剪贴板进行更多的练习。请在此处查看更多信息:
取消阻止剪贴板访问
In 2018, here's how you can go about it:
It is used in my Angular 6+ code like so:
If I pass in a string, it copies it. If nothing, it copies the page's URL.
More gymnastics to the clipboard stuff can be done too. See more information here:
Unblocking Clipboard Access
JavaScript/TypeScript 中最好、最简单的方法是使用此命令,
只需将要复制到 textExample 中的剪贴板的值传递给您即可
Best and Easy way in JavaScript/TypeScript use this command
just pass your value what you want to copy to clipboard in textExample
我不愿意对此添加另一个答案,但为了帮助像我这样的菜鸟,而且因为这是我会的 Google 最高结果。
2022 年,要将文本复制到剪贴板,您可以使用一行。
这将返回一个 Promise,如果复制则解决该 Promise,如果失败则拒绝。
完整的工作功能是这样的:
警告! 如果您在测试时打开了 Chrome 开发工具,它将失败,因为浏览器要启用剪贴板,需要您将窗口置于焦点中。这是为了防止随机网站在您不想要的情况下更改您的剪贴板。开发工具抢走了这个焦点,因此靠近开发工具,您的测试就会起作用。
如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。
https://developer.mozilla.org/en-US/docs/Web /API/Clipboard_API
这在浏览器中得到了很好的支持,您可以使用它。如果您担心 Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。 https://developer.mozilla.org/en-US/docs /Web/API/权限/查询
I am loath to add another answer on this, but to help rookies like me, and because this is the top Google result I will.
In 2022 to copy text to the clipboard you use one line.
This returns a Promise that is resolved if it copies, or rejects if it fails.
A full working function is this:
WARNING! If you have Chrome Dev Tools open while testing this it will fail because for the browser to enable the clipboard, it requires you to have the window in focus. This is to prevent random websites changing your clipboard if you don't want it. Dev Tools steals this focus so close Dev Tools and your test will work.
If you want to copy other things (images, etc) to the clipboard, look at these docs.
https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API
This is well supported enough in browsers you can use it. If you are worried about Firefox, use a Permissions Query to show or hide the button if the browser supports it. https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query
ZeroClipboard 是我发现的最好的跨浏览器解决方案:
如果您需要 iOS 的非 Flash 支持,您只需添加一个后备:
http://zeroclipboard.org/
https://github.com/zeroclipboard/ZeroClipboard
ZeroClipboard is the best cross-browser solution I've found:
If you need non-Flash support for iOS you just add a fall-back:
http://zeroclipboard.org/
https://github.com/zeroclipboard/ZeroClipboard
由于 Chrome 42+ 和 Firefox 41+ 现在支持 document.execCommand('copy') 命令,我使用 < 的组合创建了几个用于跨浏览器复制到剪贴板功能的函数a href="https://stackoverflow.com/a/8024509/4307527">Tim Down 的旧答案 和 Google 开发者的回答:
Since Chrome 42+ and Firefox 41+ now support the document.execCommand('copy') command, I created a couple of functions for a cross-browser copy-to-clipboard ability using a combination of Tim Down's old answer and Google Developer's answer:
我把我认为最好的放在一起。
这是:
用法:
copyToClipboard('some text')
I've put together what I think is the best one.
Here it is:
Usage:
copyToClipboard('some text')
其他方法将纯文本复制到剪贴板。要复制 HTML(即,您可以将结果粘贴到所见即所得编辑器中),您可以仅在 Internet Explorer 中执行以下操作。这与其他方法有根本的不同,因为浏览器实际上是可见地选择内容的。
The other methods will copy plain text to the clipboard. To copy HTML (i.e., you can paste results into a WYSIWYG editor), you can do the following in Internet Explorer only. This is is fundamentally different from the other methods, as the browser actually visibly selects the content.
我找到了以下解决方案:
按键处理程序创建一个“pre”标签。我们将内容设置为复制到此标签,然后对此标签进行选择并在处理程序中返回 true。这会调用 Chrome 的标准处理程序并复制选定的文本。
如果需要,您可以为恢复先前选择的功能设置超时。我在 MooTools 上的实现:
用法:
在粘贴时,它会创建一个文本区域并以相同的方式工作。
PS:也许这个解决方案可以用于创建一个完整的跨浏览器解决方案,无需 Flash。它适用于 Firefox 和 Chrome。
I found the following solution:
The on-key-down handler creates a "pre" tag. We set the content to copy to this tag, and then make a selection on this tag and return true in the handler. This calls the standard handler of Chrome and copies selected text.
And if you need it, you may set the timeout for a function for restoring the previous selection. My implementation on MooTools:
Usage:
On paste, it creates a textarea and works the same way.
PS: Maybe this solution can be used for creating a full cross-browser solution without Flash. It works in Firefox and Chrome.
此代码于 2021 年 5 月进行了测试。适用于 Chrome、IE、Edge。下面的“message”参数是您要复制的字符串值。
This code tested @ 2021 May . Work on Chrome , IE , Edge. 'message' parameter on below is the string value you want to copy.
使用最新的 Clipboard API 即可立即生效用户交互:
This works straight away, using the newest Clipboard API, and a user interaction:
将文本从 HTML 输入复制到剪贴板:
注意: Internet Explorer 9 及更早版本不支持
document.execCommand()
方法。来源:< a href="https://www.w3schools.com/howto/howto_js_copy_clipboard.asp" rel="nofollow noreferrer">W3Schools - 将文本复制到剪贴板
Copy text from HTML input to the clipboard:
Note: The
document.execCommand()
method is not supported in Internet Explorer 9 and earlier.Source: W3Schools - Copy Text to Clipboard
复制文本字段内文本的最佳方法。
使用navigator.clipboard.writeText。
Best Way to Copy the text inside the text field.
Use navigator.clipboard.writeText.
我在从(类似 Excel 的东西)构建自定义网格编辑以及与 Excel 的兼容性时遇到了同样的问题。我必须支持选择多个单元格、复制和粘贴。
解决方案:创建一个文本区域,您将在其中插入数据以供用户复制(对我来说,当用户选择单元格时),将焦点置于其上(例如,当用户按 Ctrl 时)并选择全文。
因此,当用户按下 Ctrl+C 时,他/她会复制他/她选择的单元格。经过测试后,只需将文本区域大小调整为一个像素(我没有测试它是否可以在显示上工作:无)。它在所有浏览器上都能很好地工作,并且对用户是透明的。
粘贴 - 你可以像这样做同样的事情(根据你的目标而不同) - 专注于文本区域并使用 onpaste 捕获粘贴事件(在我的项目中,我在单元格中使用文本区域进行编辑)。
我无法粘贴示例(商业项目),但你明白了。
I had the same problem building a custom grid edit from (something like Excel) and compatibility with Excel. I had to support selecting multiple cells, copying and pasting.
Solution: create a textarea where you will be inserting data for the user to copy (for me when the user is selecting cells), set focus on it (for example, when user press Ctrl) and select the whole text.
So, when the user hit Ctrl+C he/she gets copied cells he/she selected. After testing just resizing the textarea to one pixel (I didn't test if it will be working on display:none). It works nicely on all browsers, and it is transparent to the user.
Pasting - you could do same like this (differs on your target) - keep focus on textarea and catch paste events using onpaste (in my project I use textareas in cells to edit).
I can't paste an example (commercial project), but you get the idea.
这是Chase Seibert 的答案的扩展,优点是它适用于 IMAGE 和 TABLE 元素,而不仅仅是 Internet Explorer 9 上的 DIV。
This is an expansion of Chase Seibert's answer, with the advantage that it will work for IMAGE and TABLE elements, not just DIVs on Internet Explorer 9.
我使用过clipboard.js。
我们可以在 npm 上获取它:
也可以在 Bower 上
获取它
更多使用和示例位于 https://zenorocha.github.io/clipboard.js/。
I have used clipboard.js.
We can get it on npm:
And also on Bower
More usage & examples are at https://zenorocha.github.io/clipboard.js/.
我的不好。这仅适用于 Internet Explorer。
这是复制文本的另一种方法:
My bad. This only works in Internet Explorer.
Here's yet another way to copy text:
这是同一网站的简单基于 Ajax/会话的剪贴板。
请注意,必须启用会话并且必须启用该会话。有效,并且该解决方案适用于同一站点。我在 CodeIgniter 上测试了它,但遇到了 session/Ajax 问题,但是 this< /a> 也解决了这个问题。如果您不想使用会话,请使用数据库表。
JavaScript/jQuery
HTML 内容
PHP 代码
Here is the simple Ajax/session based clipboard for the same website.
Note that the session must be enabled & valid and this solution works for the same site. I tested it on CodeIgniter, but I ran into session/Ajax problem, but this solved that problem too. If you don't want to play with sessions, use a database table.
JavaScript/jQuery
HTML content
PHP code