如何将文本复制到剪贴板(多浏览器)?

相关:Trello如何访问用户的剪贴板?


当前回答

其他方法将纯文本复制到剪贴板。要复制HTML(即,可以将结果粘贴到所见即所得编辑器中),只能在Internet Explorer中执行以下操作。这与其他方法有根本不同,因为浏览器实际上可以直观地选择内容。

// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}
editableDiv.appendChild(someContentElement);

// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");

// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();

其他回答

我不愿意就此再加一个答案,但我想帮助像我这样的菜鸟,因为这是谷歌排名第一的结果。

在2022年,要将文本复制到剪贴板,您需要使用一行。

navigator.clipboard.writeText(textToCopy);

这将返回一个Promise,如果它复制,则该Promise将被解析,如果失败,则该Promise将被拒绝。

完整的工作功能如下:

async function copyTextToClipboard(textToCopy) {
    try {
        await navigator.clipboard.writeText(textToCopy);
        console.log('copied to clipboard')
    } catch (error) {
        console.log('failed to copy to clipboard. error=' + error);
    }
}

警告!如果您在测试时打开了Chrome开发工具,它将失败,因为浏览器要启用剪贴板,需要将窗口聚焦。这是为了防止随意网站更改剪贴板(如果你不想的话)。开发工具窃取了这一焦点,所以关闭开发工具,你的测试就会成功。

如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。

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

这在浏览器中得到了很好的支持,您可以使用它。如果您担心Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query

JavaScript/TypeScript中最简单的方法是使用此命令

navigator.clipboard.writeText(textExample);

只需在textExample中传递要复制到剪贴板的值

复制文本字段内文本的最佳方法。使用navigator.clipboard.writeText。

<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>

<script>
function myFunction() {
  var copyText = document.getElementById("myId");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
}

</script>

以下方法适用于Chrome、Firefox、Internet Explorer和Edge以及Safari的最新版本(2016年10月发布的第10版增加了复制支持)。

创建一个文本区域,并将其内容设置为要复制到剪贴板的文本。将文本区域附加到DOM。在文本区域中选择文本。调用document.execCommand(“copy”)从dom中删除文本区域。

注意:您不会看到文本区域,因为它是在Javascript代码的同一同步调用中添加和删除的。

如果您自己执行此操作,请注意以下事项:

出于安全原因,这只能从事件处理程序(如单击)调用(与打开窗口一样)。首次更新剪贴板时,Internet Explorer将显示权限对话框。Internet Explorer和Edge将在文本区域聚焦时滚动。execCommand()在某些情况下可能抛出。除非您使用文本区域,否则换行符和制表符可能会被吞入。(大多数文章似乎都建议使用div)当显示Internet Explorer对话框时,文本区域将可见,您需要隐藏它,或使用Internet Explorer特定的剪贴板数据API。在Internet Explorer中,系统管理员可以禁用剪贴板API。

下面的函数应该尽可能干净地处理以下所有问题。如果您发现任何问题或有任何改进建议,请留言。

// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and Internet Explorer 10+.
// Internet Explorer: The clipboard feature may be disabled by
// an administrator. By default a prompt is shown the first
// time the clipboard is used (per session).
function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // Internet Explorer-specific code path to prevent textarea being shown while dialog is visible.
        return window.clipboardData.setData("Text", text);

    }
    else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in Microsoft Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        }
        catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return prompt("Copy to clipboard: Ctrl+C, Enter", text);
        }
        finally {
            document.body.removeChild(textarea);
        }
    }
}

https://jsfiddle.net/fx6a6n6x/

从网页读取和修改剪贴板会引发安全和隐私问题。然而,在Internet Explorer中,可以这样做。我找到了以下示例片段:

<script type=“text/javascript”>函数select_all(obj){var text_val=评估(对象);text_val.focus();text_val.select();r=text_val.createTextRange();if(!r.execCommand)return;//特征检测r.execCommand('copy');}</script><输入值=“http://www.sajithmr.com"onclick=“select_all(this)”name=“url”type=“text”/>