javascript – 使用document.execCommand(‘copy’)复制到剪贴板失败并显示大文本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript – 使用document.execCommand(‘copy’)复制到剪贴板失败并显示大文本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2518字,纯文字阅读大概需要4分钟。
内容图文
![javascript – 使用document.execCommand(‘copy’)复制到剪贴板失败并显示大文本](/upload/InfoBanner/zyjiaocheng/702/9622aed867c84d9798ce2c668abe742b.jpg)
我正在使用隐藏文本区域放置一些文本,选择它然后使用document.execCommand将其复制到剪贴板.这通常有效但在文本很大时失败(返回false).在Chrome v55中,它似乎在180K字符左右失败.
可以通过这种方式复制的数据量是否有限制?正常Ctrl C似乎不受相同的限制.
注意:有人将此标记为Does document.execCommand(‘copy’) have a size limitation?的可能副本.这可能是类似的问题,但是那个被标记为我不使用的特定框架,而且,它没有被回答.我相信我的问题更为笼统,仍然具有相关性.
我附上代码以供参考.
function copyTextToClipboard(text) {
var textArea = document.createElement('textarea');
textArea.style.position = 'fixed';
textArea.style.top = 0;
textArea.style.left = 0;
textArea.style.width = '2em';
textArea.style.height = '2em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
解决方法:
问题与渲染这个长文本所花费的时间有关,而不是execCommand(‘copy’)调用本身.
Firefox提出了一个非常明确的错误消息:
document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.
您的代码生成文本所需的时间太长,因此浏览器不会将其识别为半可信事件…
然后解决方案是首先生成此文本,并且仅在收听用户手势以调用execCommand之后.为了使它成为可能,你可以例如听一个mousedown事件来生成文本,只有在mouseup事件中才能真正执行copy命令.
const text = ('some text a bit repetitive ' + Date.now()).repeat(50000);
function copyTextToClipboard(text) {
// first we create the textArea
var textArea = document.createElement('textarea');
textArea.style.position = 'absolute';
textArea.style.opacity = '0';
textArea.value = text;
document.body.appendChild(textArea);
var execCopy = e => { // triggered on mouseup
textArea.select();
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
console.log('Copying text command was ' + msg);
document.body.removeChild(textArea);
};
// here the magic
btn.addEventListener('mouseup', execCopy, {
once: true
});
}
// triggered on mousedown
btn.onmousedown = e => copyTextToClipboard(text);
<button id="btn">copy some text in your clipboard</button>
<p>May struggle your browser a little bit, it's quite a long text... Please be patient</p>
内容总结
以上是互联网集市为您收集整理的javascript – 使用document.execCommand(‘copy’)复制到剪贴板失败并显示大文本全部内容,希望文章能够帮你解决javascript – 使用document.execCommand(‘copy’)复制到剪贴板失败并显示大文本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。