Copy clipboard

I am testing the url above…
if I click the button “Copy text”, ​the mouse copy the text in the text field.
It works fine at the url above.
However it doesn’t work fine at http://dot.kr/Q/copyButton/11.php.
although the code in both file are same.

What’s wrong?
How can I make it work fine?

If you look at the console you’ll see it gives an error when you click the copy button.

Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')
    at myFunction (11.php:63)
    at HTMLButtonElement.onclick (11.php:52)

Maybe the code isn’t the same in both files?

What is different above and below the code in the php file?

Hi @joon1, the reason why this doesn’t work on your page is that the clipboard interface is only available when the page is served over HTTPS – on non-secure contexts it’s simply undefined, hence the error @Gandalf mentioned. So you should add a guard to check if navigator.clipboad is actually available:

function myFunction() {
  if (!navigator.clipboard) return

  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
  
  var tooltip = document.getElementById("myTooltip");
  tooltip.innerHTML = "Copied: " + copyText.value;
}

Note that the localhost is in fact considered a secure context, so you can still test your code on a local dev server… as for instance the one that comes with PHP:

php -S localhost:8080
2 Likes

As I test it at localhost, it works fine. Thank you.

I add the code above at http://dot.kr/Q/copyButton/12.php
However it seems not to work.
What’s wrong?

Well it does work in that your script doesn’t throw an error any more… the clipboard still won’t be available on HTTP pages though.

I see. then I need to use HTTPS in my pages.