将 JavaScript 变量的输出复制到剪贴板

Copy output of a JavaScript variable to the clipboard

我不了解 JavaScript,但我设法使用各种 Stack Overflow 答案中的位和螺栓将这段代码组合在一起。它工作正常,并通过警告框输出文档中所有选中复选框的数组。

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  return checkbx;
}

我使用:

来称呼它
<button id="btn_test" type="button" >Check</button>
<script>
    document.getElementById('btn_test').onclick = function() {
        var checkedBoxes = getSelectedCheckboxes("my_id");
        alert(checkedBoxes);
    }
</script>

现在我想修改它,所以当我单击 btn_test 按钮时,输出数组 checkbx 被复制到剪贴板。我尝试添加:

checkbx = document.execCommand("copy");

checkbx.execCommand("copy");

在函数的末尾,然后像这样调用它:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('my_id')">Check</button>

但是没有用。没有数据复制到剪贴板。

好的,我找了一些时间并按照 Teemu 的建议进行了操作,我能够得到我想要的东西。

所以这里是任何可能感兴趣的人的最终代码。为了清楚起见,此代码获取某个 ID 的所有选中复选框,将它们输出到一个数组中,此处命名为 checkbx,然后将它们的唯一名称复制到剪贴板。

JavaScript函数:

function getSelectedCheckboxes(chkboxName) {
  var checkbx = [];
  var chkboxes = document.getElementsByName(chkboxName);
  var nr_chkboxes = chkboxes.length;
  for(var i=0; i<nr_chkboxes; i++) {
    if(chkboxes[i].type == 'checkbox' && chkboxes[i].checked == true) checkbx.push(chkboxes[i].value);
  }
  checkbx.toString();

  // Create a dummy input to copy the string array inside it
  var dummy = document.createElement("input");

  // Add it to the document
  document.body.appendChild(dummy);

  // Set its ID
  dummy.setAttribute("id", "dummy_id");

  // Output the array into it
  document.getElementById("dummy_id").value=checkbx;

  // Select it
  dummy.select();

  // Copy its contents
  document.execCommand("copy");

  // Remove it as its not needed anymore
  document.body.removeChild(dummy);
}

及其 HTML 调用:

<button id="btn_test" type="button" onclick="getSelectedCheckboxes('ID_of_chkbxs_selected')">Copy</button>

很有用。我修改它以将一个 JavaScript 变量值复制到剪贴板:

function copyToClipboard(val){
    var dummy = document.createElement("input");
    dummy.style.display = 'none';
    document.body.appendChild(dummy);

    dummy.setAttribute("id", "dummy_id");
    document.getElementById("dummy_id").value=val;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    // to avoid breaking orgain page when copying more words
    // cant copy when adding below this code
    // dummy.style.display = 'none'
    document.body.appendChild(dummy);
    //Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')

为了将任何文本复制到剪贴板的一般目的,我编写了以下函数:

function textToClipboard (text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

参数的值被插入到新创建的 <textarea> 的值中,然后选择它,它的值被复制到剪贴板,然后从文档中删除。

我只想补充一点,如果有人想将两个不同的输入复制到剪贴板。我还使用了将其放入变量的技术,然后将来自两个输入的变量的文本放入文本区域。

注意:下面的代码来自一位询问如何将多个用户输入复制到剪贴板的用户。我刚刚修复它以使其正常工作。所以期待一些旧的风格,比如使用 var 而不是 letconst。我还建议使用 addEventListener 作为按钮。

    function doCopy() {

        try{
            var unique = document.querySelectorAll('.unique');
            var msg ="";

            unique.forEach(function (unique) {
                msg+=unique.value;
            });

            var temp =document.createElement("textarea");
            var tempMsg = document.createTextNode(msg);
            temp.appendChild(tempMsg);

            document.body.appendChild(temp);
            temp.select();
            document.execCommand("copy");
            document.body.removeChild(temp);
            console.log("Success!")


        }
        catch(err) {

            console.log("There was an error copying");
        }
    }
<input type="text" class="unique" size="9" value="SESA / D-ID:" readonly/>
<input type="text" class="unique" size="18" value="">
<button id="copybtn" onclick="doCopy()"> Copy to clipboard </button>

当你需要在 Chrome 开发控制台中将变量复制到剪贴板时,你可以简单地使用 copy() 命令。

https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject

我通过添加 隐藏 input 元素成功地将文本复制到剪贴板(没有显示任何文本框)到 body,即:

 function copy(txt){
  var cb = document.getElementById("cb");
  cb.value = txt;
  cb.style.display='block';
  cb.select();
  document.execCommand('copy');
  cb.style.display='none';
 }
<button onclick="copy('Hello Clipboard!')"> copy </button>
<input id="cb" type="text" hidden>

在撰写本文时,在元素上设置 display:none 对我来说没有用。将元素的宽度和高度设置为 0 也不起作用。因此元素的宽度必须至少为 1px 才能正常工作。

以下示例适用于 Chrome 和 Firefox:

    const str = 'Copy me';
    const el = document.createElement("input");
    // Does not work:
    // dummy.style.display = "none";
    el.style.height = '0px';
    // Does not work:
    // el.style.width = '0px';
    el.style.width = '1px';
    document.body.appendChild(el);
    el.value = str;
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);

我想补充一点,我明白为什么浏览器会试图阻止这种骇人听闻的方法。最好公开显示您要复制到用户浏览器中的内容。但是有时候有设计要求,我们也改不了。

现在 new(ish) API 可以直接执行此操作。它仅适用于现代浏览器和 HTTPS(和本地主机)。 IE11 不支持。

IE11 有自己的 API.

接受的答案中的解决方法可用于不安全的主机。

function copyToClipboard (text) {
  if (navigator.clipboard) { // default: modern asynchronous API
    return navigator.clipboard.writeText(text);
  } else if (window.clipboardData && window.clipboardData.setData) {     // for IE11
    window.clipboardData.setData('Text', text);
    return Promise.resolve();
  } else {
    // workaround: create dummy input
    const input = h('input', { type: 'text' });
    input.value = text;
    document.body.append(input);
    input.focus();
    input.select();
    document.execCommand('copy');
    input.remove();
    return Promise.resolve();
  }
}

注意:它使用 Hyperscript 创建输入元素(但应该很容易适应)

没有必要让输入不可见,因为它添加和删除的速度非常快。此外,当隐藏时(即使使用一些聪明的方法),一些浏览器也会检测到它并阻止复制操作。

function CopyText(toCopy, message) {
    var body = $(window.document.body);
    var textarea = $('<textarea/>');
    textarea.css({
        position: 'fixed',
        opacity: '0'
    });

    textarea.val(toCopy);
    body.append(textarea);
    textarea[0].select();

    try {
        var successful = document.execCommand('copy');
        if (!successful)
            throw successful;
        else
            alert(message);
    } catch (err) {
        window.prompt("Copy to clipboard: Ctrl+C, Enter", toCopy);
    }

    textarea.remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<button type="button" onClick="CopyText('Hello World', 'Text copped!!')">Copy</button>

使用剪贴板API

text = "HEllo World";
navigator.clipboard.writeText(text)

它适用于 Chrome 66+、Edge 79+、Firefox 63+,但不适用于 I.E.

阅读有关剪贴板的更多信息 API 在 MDN Docs