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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33855641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:34:21  来源:igfitidea点击:

Copy output of a JavaScript variable to the clipboard

javascriptcopyclipboard

提问by harman

I have no knowledge of JavaScript, but I managed to put this code together using bits and bolts from various Stack Overflow answers. It works OK, and it outputs an array of all selected checkboxes in a document via an alert box.

我对 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;
}

And to call it I use:

并称之为我使用:

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

Now I would like to modify it so when I click the btn_testbutton the output array checkbxis copied to the clipboard. I tried adding:

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

checkbx = document.execCommand("copy");

or

或者

checkbx.execCommand("copy");

at the end of the function and then calling it like:

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

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

But it does not work. No data is copied to clipboard.

但它不起作用。没有数据被复制到剪贴板。

采纳答案by harman

OK, I found some time and followed the suggestion by Teemuand I was able to get exactly what I wanted.

好的,我找到了一些时间并遵循了Teemu的建议,我能够得到我想要的东西。

So here is the final code for anyone that might be interested. For clarification, this code gets all checked checkboxes of a certain ID, outputs them in an array, named here checkbx, and then copies their unique name to the clipboard.

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

JavaScript function:

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);
}

And its HTML call:

以及它的 HTML 调用:

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

回答by walkman

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')

回答by Peter Paulovics

For general purposes of copying any text to the clipboard, I wrote the following function:

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

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

The value of the parameter is inserted into value of a newly created <textarea>, which is then selected, its value is copied to the clipboard and then it gets removed from the document.

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

回答by lbrutti

Very useful. I modified it to copy a JavaScript variable value to clipboard:

很有用。我修改它以将 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);
}

回答by Evgeny

When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy()command.

当您需要在 Chrome 开发控制台中将变量复制到剪贴板时,您只需使用该copy()命令即可。

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

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

回答by CONvid19

I managed to copy text to the clipboard (without showing any text boxes) by adding a hiddeninputelement to body, i.e.:

通过向 中添加隐藏元素,我设法将文本复制到剪贴板(不显示任何文本框),即:inputbody

 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>

回答by sr9yar

At the time of writing, setting display:noneon the element didn't workfor me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1pxin width for this to work.

在撰写本文时,元素上的设置display:none不起作用。将元素的宽度和高度设置为 0 也不起作用。所以元素必须至少1px在宽度上才能工作。

The following example worked in Chrome and Firefox:

以下示例适用于 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);

I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.

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

回答by Richard Ramos

I just want to add, if someone wants to copy two different inputs to clipboard. I also used the technique of putting it to a variable then put the text of the variable from the two inputs into a text area.

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

Note:the code below is from a user asking how to copy multiple user inputs into clipboard. I just fixed it to work correctly. So expect some old style like the use of varinstead of letor const. I also recommend to use addEventListenerfor the button.

注意:下面的代码来自用户询问如何将多个用户输入复制到剪贴板。我只是修复了它才能正常工作。所以期待一些旧的风格,比如使用 ofvar而不是letor const。我也建议使用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>