为什么使用JavaScript无法复制到剪贴板? [英] Why copy to clipboard doesn't work using JavaScript?

查看:86
本文介绍了为什么使用JavaScript无法复制到剪贴板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试此功能:

function copyToClipboard(str) {

const el = document.createElement('textarea');
el.textContent = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
    document.getSelection().rangeCount > 0 ?
    document.getSelection().getRangeAt(0) :
    false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
}
alert("Success");}

我尝试了el.value = str;也.我在做什么错了?

I've tried with el.value = str; too. What am I doing wrong?

推荐答案

document.execCommand 已被弃用,但仍可在Web浏览器中访问

The document.execCommand has been deprecated but still accessible across web browsers

navigator.clipboard API 您将要复制的文本传递到剪贴板中

You pass in the text to be copied to the clipboard like so

navigator.clipboard.writeText(str_to_copy).then(success_callback, failure_callback);

请注意,此选项卡必须处于活动状态,否则您将无权复制剪贴板

该API是异步的,因此您可以使用 .then 回调向用户发出警报,无论复制剪贴板是否成功.查看我可以使用在网络浏览器中的可用性.

The API is asynchronous so you can use the .then callback to alert the user if copying the clipboard was successful or not. Check out the Can I Use for its availability across web browsers.

这篇关于为什么使用JavaScript无法复制到剪贴板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆