最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Copy text to the clipboard with PHP and JavaScript? - Stack Overflow

programmeradmin6浏览0评论

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' <[email protected]>, 'Brad Majors' <[email protected]>, 'Frank N. Furter' <[email protected]>

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>

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' <[email protected]>, 'Brad Majors' <[email protected]>, 'Frank N. Furter' <[email protected]>

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>
Share Improve this question edited Jun 8, 2018 at 20:18 Bear. Teddy Bear. asked Jun 6, 2018 at 21:10 Bear. Teddy Bear.Bear. Teddy Bear. 1491 gold badge2 silver badges12 bronze badges 7
  • Are you sure you want to expose those email addresses? – GolezTrol Commented Jun 6, 2018 at 21:14
  • 3 @GolezTrol Those email addresses represent fictional characters. See Rocky Horror Picture Show. Valid concern though :) – Burgan Commented Jun 6, 2018 at 21:17
  • @Flashdrive Valid concern, because it is an existing domain (of the RHPS fanclub actually), and therefore maybe existing e-mail addresses too. And if this is indeed the code of that website, this question also exposed that it uses an old version of PHP which doesn't get any patches anymore, and a piece of code that seems to be vulnerable to SQL injection attacks. I'd make a backup, just to be sure. ;-) – GolezTrol Commented Jun 6, 2018 at 21:17
  • In that line were echo in span it should be class="mono" missing quotes – Michael Commented Jun 6, 2018 at 21:18
  • I just made up the emails. – Bear. Teddy Bear. Commented Jun 7, 2018 at 14:26
 |  Show 2 more comments

3 Answers 3

Reset to default 13

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>

You can't copy directly from a string, only from an HTML element. You need to put the PHP string into the value of the element.

function copyToClipboardWithJavascript() {
  /* Get the text field */
  var copyText = document.getElementById("theList");
  /* Put emails into the text field */
  copyText.value = <?php echo json_encode($emails); ?>;
  /* Select the text field */
  copyText.select();
  /* Copy the text inside the text field */
  document.execCommand("copy");
}

This simple solution may work for you. It is what I use. With jQuery.

function copy() {
  navigator.clipboard.writeText($('#link-to-copy').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span onclick="copy();">
  Copy link
</span>

<input type="hidden" id="link-to-copy" value="<?= $link_copy ?>">

When you click the "Copy link" span element, it will call the copy() function which will then write the value of the hidden input (with the id of 'link-to-copy') to the clipboard of your navigator.

The value of the hidden input can be whatever you want, here I am using a PHP variable. This PHP value will then be copied to you clipboard.

发布评论

评论列表(0)

  1. 暂无评论