Landmine
Landmine

Reputation: 1789

What could be preventing Javascript from storing the value on the clipboard?

I'm using some simple Javascript in my ASP.Net website.

A value gets calculated and stored in a hidden textbox as shown below.

<asp:LinkButton ID="LinkButtonShare" runat="server" CssClass="btn btn-success" OnClientClick="copyToClipboard()"><i class="fa fa-share-square"></i> Share</asp:LinkButton>
<div class="hidden"><asp:TextBox ID="TextBoxCopyURL" runat="server" ClientIDMode="Static"></asp:TextBox></div>

Then it executes my Javascript as shown below.

function copyToClipboard() {
  var copyText = document.getElementById("TextBoxCopyURL");
  copyText.select();
  document.execCommand("copy");

  /* Alert with the copied text */
  alert("Copied the text: " + copyText.value);

Resulting in an alert that looks like the following, but the string is never copied to my clipboard in Firefox or Chrome.

enter image description here

I cant seem to understand what I'm missing on something so simple...

Upvotes: 0

Views: 41

Answers (2)

user6749601
user6749601

Reputation:

Following the example on this page:

https://forums.asp.net/t/1106610.aspx?How+to+copy+the+text+of+a+textbox+to+clipboard+

you can solve it this way:

function copyToClipboard() {
    var copyText = document.getElementById("TextBoxCopyURL");
    copyTextValue = copyText.value;

    window.clipboardData.setData('Text' , copyTextValue );

    /* Alert with the copied text */
    alert("Copied the text: " + copyTextValue );

}

Upvotes: 1

Geuis
Geuis

Reputation: 42267

Slight variation of your code, but basically the same. It works as expected. https://codepen.io/anon/pen/ZjWXoj

function copyToClipboard() {
  var copyText = document.getElementById("textinput");
  copyText.select();
  document.execCommand("copy");

  console.log(copyText.value); // logs copyText input value
}

document.querySelector('#btn').addEventListener('click', () => {
  copyToClipboard();
})

Be aware that you can't directly get the content of the clipboard in js. i.e. You can't programmatically trigger a paste or access the content of the clipboard.

Upvotes: 2

Related Questions