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

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


当前回答

自动复制到剪贴板可能很危险,因此大多数浏览器(Internet Explorer除外)都很难做到。就我个人而言,我使用以下简单技巧:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

用户将看到提示框,其中已选择要复制的文本。现在,按下Ctrl+C和Enter键(关闭框)就足够了——瞧!

现在剪贴板复制操作是安全的,因为用户手动执行(但方式非常简单)。当然,它适用于所有浏览器。

<button id=“demo”onclick=“copyToClipboard(document.getElementById('demo').innerHTML)”>这是我要复制的内容</button><脚本>函数复制到剪贴板(文本){window.prpt(“复制到剪贴板:Ctrl+C,Enter”,文本);}</script>

其他回答

clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用如下内容:

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>

clipboard.js也在GitHub上。

注意:现在已弃用此选项。迁移到此处。

从网页读取和修改剪贴板会引发安全和隐私问题。然而,在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”/>

2018年,你可以这样做:

async copySomething(text?) {
  try {
    const toCopy = text || location.href;
    await navigator.clipboard.writeText(toCopy);
    console.log('Text or Page URL copied');
  }
  catch (err) {
    console.error('Failed to copy: ', err);
  }
}

它在我的Angular 6+代码中使用如下:

<button mat-menu-item (click)="copySomething()">
    <span>Copy link</span>
</button>

如果我传入一个字符串,它就会复制它。如果没有,它会复制页面的URL。

也可以在剪贴板上做更多的体操。在此处查看更多信息:

取消阻止剪贴板访问

我非常成功地使用了这个(没有jQuery或任何其他框架)。

function copyToClp(txt){
    var m = document;
    txt = m.createTextNode(txt);
    var w = window;
    var b = m.body;
    b.appendChild(txt);
    if (b.createTextRange) {
        var d = b.createTextRange();
        d.moveToElementText(txt);
        d.select();
        m.execCommand('copy');
    } 
    else {
        var d = m.createRange();
        var g = w.getSelection;
        d.selectNodeContents(txt);
        g().removeAllRanges();
        g().addRange(d);
        m.execCommand('copy');
        g().removeAllRanges();
    }
    txt.remove();
}

警告

制表符转换为空格(至少在Chrome中)。

其他方法将纯文本复制到剪贴板。要复制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();