Javascript – Copy text to the clipboard with PHP and JavaScript

clipboardhtmljavascriptphp

I want to include a button on an existing webpage that will copy text to the Windows clipboard.

The webpage and the PHP in it already works well to create and display text like this:

Output on webpage:

'Abby Normal' <abnormal@rockyhorror.com>, 'Brad Majors' <bm@rockyhorror.com>, 'Frank N. Furter' <franknfurter@rockyhorror.com>

So now I want to add a Javascript function and an html button that calls that function to copy that output to the Windows clipboard.

Problem: nothing is copied when the button is pressed. What am I doing wrong? Thank you in advance.

<?PHP
  session_start();
  include('include/_initsess.php');
  include('include/_setdb.php');
  if(!isset($_SESSION['userlist'])) exit;
  $users = $_SESSION['userlist'];
  $emails = '';
  $qry = "SELECT FIRST,LAST,EMAIL FROM users WHERE PKEY IN ($users)";
  $result  = mysql_query($qry);     
  $numrows = mysql_num_rows($result);   
  for ($m=0; $m<$numrows; $m++) {
    $row = mysql_fetch_array($result); 
    list($fn,$ln,$em) = $row;
    $emails .= ($m==0) ? "'".$fn." ".$ln."' &lt;".$em."&gt;" : (", '".$fn." ".$ln."' &lt;".$em."&gt;");
    } // end for
?>

<html>
<head>
</head>
<body>
<span class=mono id="theList" value="<?php echo $emails; ?>">
  <?PHP echo($emails); ?>
</span>

<script>
function copyToClipboardWithJavascript() {
  /* Get the text field */
  var copyText = document.getElementById("theList");
  /* Select the text field */
  copyText.select();
  /* Copy the text inside the text field */
  document.execCommand("copy");
}
</script>

<button onclick="copyToClipboardWithJavascript()">Click here</button>

</span>
</body>
</html>

I've tried the way a Javascript tutorial suggested:

var copyText = = document.getElementById("theList");

And my own variations using PHP within Javascript:

var copyText = <?PHP echo($emails); ?>;
var copyText = `<?PHP echo($emails); ?>`;
var copyText = "<?PHP echo($emails); ?>";
var copyText = '<?PHP echo($emails); ?>';

But the result is that nothing causes any errors and nothing is copied to the clipboard.

I know the web page is being immediately saved and used because I also make a trivial change to the letters 'Click here' in the button and can see the difference after refreshing.enter code here

***UPDATE WITH ANSWER I USED:****

<span class=mono id="theList">
<?PHP echo($emails); ?>
</span>
<button id="copyButton" onclick="myCopyFunction()">Copy email address list to clipboard.</button>
<script>
function myCopyFunction() {
  var myText = document.createElement("textarea")
  myText.value = document.getElementById("theList").innerHTML;
  myText.value = myText.value.replace(/&lt;/g,"<");
  myText.value = myText.value.replace(/&gt;/g,">");
  document.body.appendChild(myText)
  myText.focus();
  myText.select();
  document.execCommand('copy');
  document.body.removeChild(myText);
}
</script>

Best Solution

Here is a working example I made:

There are two things you need to know.

  1. Contrary to the previous answer, you CAN actually copy a variable string to the clipboard, as shown in my example.
  2. The user MUST EXPLICITLY take an action which causes the copy function to be called. If it is called automatically, the copy will be denied. This is most likely the cause of your problem.

Here is my example. To briefly explain how this works: a new temporary element of type input type='text' is created, given the value to copy to the clipboard, then the copy command is executed, then that temporary item is removed.

copyToClipboard(document.getElementById("content"));

document.getElementById("clickCopy").onclick = function() {
	copyToClipboard(document.getElementById("goodContent"));
}

document.getElementById("clickCopyString").onclick = function() {
	copyToClipboard("This is a variable string");
}

/**
* This will copy the innerHTML of an element to the clipboard
* @param element reference OR string
*/
function copyToClipboard(e) {
    var tempItem = document.createElement('input');

    tempItem.setAttribute('type','text');
    tempItem.setAttribute('display','none');
    
    let content = e;
    if (e instanceof HTMLElement) {
    		content = e.innerHTML;
    }
    
    tempItem.setAttribute('value',content);
    document.body.appendChild(tempItem);
    
    tempItem.select();
    document.execCommand('Copy');

    tempItem.parentElement.removeChild(tempItem);
}
div {
  border: 1px solid black;
  margin: 10px;
  padding: 5px;
}
<div id="content">
This is example text which will NOT be copied to the clipboard.
</div>
<div id="goodContent">
This WILL be copied to the cliboard when you push the button below:
</div>
<button id="clickCopy">
Copy Text from 2nd
</button>

<button id="clickCopyString">
Copy STRING to Clibpoard from Variable
</button>