复制事件中的event.clipboardData.setData [英] event.clipboardData.setData in copy event
问题描述
我看过很多帖子,但是对于以下两个问题找不到明确的答案,因为看起来标准和浏览器支持一直在不断变化。
-
根据标准,使用'copy'事件处理程序中的event.clipboardData.setData更改剪贴板是合法操作吗?
-
最新版本的Chrome / FF / Safari / IE / Chrome iOS / Android / iPhone是否支持此功能?
谢谢!
截至2016年,剪贴板API确实在积极开发中,但这是我对当前状态的理解使用event.clipboardData.setData()支持
用<$ c $更改剪贴板c> event.clipboardData.setData()在规范允许的'copy'
事件处理程序内(只要事件不是< a href =https://developer.mozilla.org/en-US/docs/Web/Guide/ Events / Creating_and_triggering_eventsrel =noreferrer> synthetic )。
请注意,您需要防止事件处理程序中的默认操作阻止您的更改被浏览器覆盖:
document.addEventListener('copy',function(e){
e.clipboardData .setData('text / plain','foo');
e.preventDefault(); //默认行为是复制任何选定的文本
});
要触发复制事件,请使用execCommand
如果您需要触发复制事件(而不仅仅是处理用户通过浏览器UI发出的复制请求),您必须使用 document.execCommand('copy')
。它只适用于某些处理程序,例如单击
处理程序:
document.getElementById(copyBtn)。onclick = function(){
document.execCommand('copy');
}
浏览器支持各不相同
- Firefox支持
副本
/剪切中的
/clipboardData
粘贴
事件(自Firefox 22 )和execCommand('copy')
来自用户操作(自Firefox 41 ) - Chrome同时支持两者(后者是在Chrome 43中添加 - 或也许42?)
- caniuse.com声称Safari(截至9.1)不支持后者。
- MS Edge平台状态列出IE / Edge不支持剪贴板API,此时详细信息的链接已被破坏。
https://github.com/garykac /clipboard/blob/master/clipboard.md 具有 execCommand(剪切/复制/粘贴)
的兼容性表。
您可以使用下面的代码段对此进行测试,请对结果进行评论。
更多资源
- 规格:剪贴板API及活动
- The使用JavaScript复制和粘贴的权威指南(2014) - 有关浏览器中剪贴板API互操作性的更多信息,包括对复制/粘贴事件的支持选择并支持多种格式。
- 在MDN上标记为Clipboard API的页面
测试用例
$ b $
window.onload = function(){document.addEventListener('copy',function(e){ console.log(复制处理程序); if(document.getElementById(enableHandler)。checked){e.clipboardData.setData('text / plain','current time is'+ new Date()); e.preventDefault(); //默认行为是复制任何选定的文本} //这只是为了简化测试:setTimeout(function(){var tb = document.getElementById(target); tb.value =; tb.focus() ;},0); }); document.getElementById(execCopy)。onclick = function(){document.execCommand('copy'); //只在click处理程序或其他用户触发的线程中有效} document.getElementById(synthEvt)。onclick = function(){var e = new ClipboardEvent(copy,{dataType:text / plain,data: 酒吧}); document.dispatchEvent(E); }}
< html>< input id = enableHandlertype =checkboxchecked>< label for =enableHandler>在copy处理程序< / label>< p>中运行clipboardData.setData('text / plain',...)尝试选择此文本并使用< / p>< ul>来触发副本< li>< button id =execCopy> document.execCommand('copy')< / button> - 应该可以工作。< / li> < li>< button id =synthEvt> document.dispatchEvent(clipboardEvent)< / button> - 不应该工作< / li> < li>使用快捷键 - 应该可以工作< / li> < li>或从上下文菜单中选择< / li>< / ul>< p>如果触发了复制处理程序,焦点将自动移动到下面的文本框,以便您可以尝试粘贴from clipboard:< / p>< input type =textid =targetsize =80>
异步剪贴板API将提供更简单的方式来管理剪贴板
实施时, navigator.clipboard
会让你编写如下代码:
navigator.clipboard.writeText('要复制的文字')
.then(()=> {
console.log('文本复制到剪贴板');
})
.catch(err = > {
//如果用户拒绝剪贴板权限,则会发生这种情况:
console.error('Could not copy text:',err);
});
Chrome 66开始发布部分实现,并且已发布关于新API的文章。
I have looked at many posts but could not find a clear current answer to the following two questions as it seems standards and browser support has been constantly changing.
Is it a legal operation according to the standard to change the clipboard with event.clipboardData.setData inside a 'copy' event handler ?
Do latest versions of Chrome/FF/Safari/IE/Chrome iOS/Android/iPhones support this correctly ?
Thanks!
Clipboard APIs are indeed in active development as of 2016, but here's my understanding of the current state of affairs.
Using event.clipboardData.setData() is supported
Changing the clipboard with event.clipboardData.setData()
inside a 'copy'
event handler is allowed by the spec (as long as the event is not synthetic).
Note that you need to prevent the default action in the event handler to prevent your changes from being overwritten by the browser:
document.addEventListener('copy', function(e){
e.clipboardData.setData('text/plain', 'foo');
e.preventDefault(); // default behaviour is to copy any selected text
});
To trigger the copy event use execCommand
If you need to trigger the copy event (and not just handle the copy requests made by the user via the browser UI), you must use document.execCommand('copy')
. It will only work in certain handlers, such as the click
handler:
document.getElementById("copyBtn").onclick = function() {
document.execCommand('copy');
}
Browser support varies
- Firefox supports both
clipboardData
in thecopy
/cut
/paste
events (since Firefox 22) andexecCommand('copy')
from user actions (since Firefox 41) - Chrome also supports both (the latter was added in Chrome 43 - or perhaps 42?)
- caniuse.com claims that Safari (as of 9.1) doesn't support the latter.
- MS Edge Platform Status lists IE/Edge as not supporting the Clipboard APIs, the link to details is broken at the moment.
https://github.com/garykac/clipboard/blob/master/clipboard.md has a compatibility table for execCommand(cut / copy / paste)
.
You can test this using the snippet below, please comment with the results.
More resources
- Specification: Clipboard API and events
- The Definitive Guide to Copying and Pasting in JavaScript (2014) - more information on clipboard API interoperability in browsers, including support for the "copy"/"paste" events without a selection and support for multiple formats.
- Pages tagged "Clipboard API" on MDN
Testcase
window.onload = function() {
document.addEventListener('copy', function(e){
console.log("copy handler");
if (document.getElementById("enableHandler").checked) {
e.clipboardData.setData('text/plain', 'Current time is ' + new Date());
e.preventDefault(); // default behaviour is to copy any selected text
}
// This is just to simplify testing:
setTimeout(function() {
var tb = document.getElementById("target");
tb.value = "";
tb.focus();
}, 0);
});
document.getElementById("execCopy").onclick = function() {
document.execCommand('copy'); // only works in click handler or other user-triggered thread
}
document.getElementById("synthEvt").onclick = function() {
var e = new ClipboardEvent("copy", {dataType: "text/plain", data:"bar"});
document.dispatchEvent(e);
}
}
<html>
<input id="enableHandler" type="checkbox" checked>
<label for="enableHandler">Run clipboardData.setData('text/plain', ...) in the "copy" handler</label>
<p>Try selecting this text and triggering a copy using</p>
<ul>
<li><button id="execCopy">document.execCommand('copy')</button> - should work.</li>
<li><button id="synthEvt">document.dispatchEvent(clipboardEvent)</button> - should NOT work</li>
<li>with keyboard shortcut - should work</li>
<li>or from the context menu - should work</li>
</ul>
<p>If the "copy" handler was triggered, the focus will move to the textbox below automatically, so that you can try pasting from clipboard:</p>
<input type="text" id="target" size="80">
Async Clipboard API will provide a simpler way to manage the clipboard
When implemented, navigator.clipboard
will let you write code like this:
navigator.clipboard.writeText('Text to be copied')
.then(() => {
console.log('Text copied to clipboard');
})
.catch(err => {
// This can happen if the user denies clipboard permissions:
console.error('Could not copy text: ', err);
});
Chrome 66 starts shipping a partial implementation, and they've published an article about the new API.
这篇关于复制事件中的event.clipboardData.setData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!