-3

I'm trying to do a button to copy a link (www.google.com) to the clipboard, but it's not working. My code is:

<script type='text/javascript'>
    function myFunction() {
      /* Get the text field */
      var copyText = document.getElementById("www.google.com");
    
      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */
    
       /* Copy the text inside the text field */
      navigator.clipboard.writeText(copyText.value);
    
      /* Alert the copied text */
      alert("Copied link!");
    }
</script>

And the button:

<button onclick='myFunction()'>Clik to copy the Link</button>
Oscar
  • 1
  • 4
  • Is the `id` of the link `www.google.com`? – Anurag Srivastava Sep 11 '21 at 15:17
  • No, I don't have ID. It's a static link, how i can do it? I just want to make a button to which when pressed, I copy the link www.google.com – Oscar Sep 11 '21 at 15:18
  • `.getElementById` finds an element with the ID you provided in the DOM. If your element doesn't have such ID then it doesn't make sense and you have to select it in some other way. – Dropout Sep 11 '21 at 15:22
  • 1
    Does this answer your question? [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – Anurag Srivastava Sep 11 '21 at 15:24
  • No, in all the examples they look for the text to be covered in some elementID. I don't want the user to see the text to be copied – Oscar Sep 11 '21 at 15:33

2 Answers2

1

This will help you


function copyToClipboard(text) {
  if (navigator.clipboard) {
    return navigator.clipboard.writeText(text);
  }

  const element = document.createElement('span');
  element.textContent = text;
  element.style.whiteSpace = 'pre';
  document.body.appendChild(element);
  const selection = window.getSelection();
  const range = document.createRange();
  selection.removeAllRanges();
  range.selectNode(element);
  selection.addRange(range);
  document.execCommand('copy');
  selection.removeAllRanges();
  document.body.removeChild(element);
}
Hai Thai
  • 294
  • 2
  • 10
0

try this with async function and await

async function copyGoogleLink(){
    await navigator.clipboard.writeText('https://www.google.com')
    .then(() => console.log('Copied'));
}

use this with Event Listener

Kofusu
  • 164
  • 1
  • 10
  • Works well on computer, but not on android – Oscar Sep 11 '21 at 15:46
  • I get: `Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'writeText') at copyLink ((index):1) at HTMLButtonElement.onclick ` – Oscar Sep 11 '21 at 15:56
  • `document.querySelector('#button').addEventListener('click', async function(event){ return await navigator.clipboard.writeText('https://www.google.com!').then(() => console.log('Coppied!')); });` try like this with return – Kofusu Sep 11 '21 at 16:04
  • Get: `(index):1 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'addEventListener') at copyLink ((index):1) at HTMLButtonElement.onclick ((index):1)` – Oscar Sep 11 '21 at 16:21
  • did you give button an id #button ? like this `` – Kofusu Sep 11 '21 at 16:26
  • Oh!!! I forgot it. Should remove the onclick='copyGoogleLink()' ?? – Oscar Sep 11 '21 at 16:30
  • remove the onclick, because onclick is already defined at JS addEventListener – Kofusu Sep 11 '21 at 16:32
  • Now without the onclick, the button doens't do anything, any error but anything copied – Oscar Sep 11 '21 at 16:36
  • on HTML button: ``, on Script JS: `document.querySelector('#button').addEventListener('click', async function(event){ return await navigator.clipboard.writeText('https://www.google.com!').then(() => console.log('Coppied!')); });`. did exactly like this? – Kofusu Sep 11 '21 at 16:40
  • There is a pic: https://paste.pics/3e9e4d5cbc7660c0c054df93518c7878 – Oscar Sep 11 '21 at 16:46
  • Sorry i dont know `const char HTTP_GENERATE_O2BASE_LINK_SCRIPT[] PROGMEM` mean – Kofusu Sep 11 '21 at 16:50
  • It's for arduino, `String page = FPSTR(HTTP_HEADER); page.replace("{v}", "Options"); page += FPSTR(HTTP_IMAGE); page += FPSTR(HTTP_SCRIPT); page += FPSTR(HTTP_GENERATE_O2BASE_LINK_SCRIPT); page += FPSTR(HTTP_STYLE); page += _customHeadElement; page += FPSTR(HTTP_HEADER_END); page += String(F("

    ")); page += _apName; page += String(F("

    ")); page += FPSTR(HTTP_PORTAL_OPTIONS); page += FPSTR(HTTP_GENERATE_O2BASE_LINK); page += FPSTR(HTTP_END);` and after I run a server with the "page" html code
    – Oscar Sep 11 '21 at 16:53
  • on that picture, dont use async function outside document.query selector. or else you use `` at a button – Kofusu Sep 11 '21 at 16:59
  • Do I remove async? – Oscar Sep 11 '21 at 17:01
  • just replace exactly like this `` – Kofusu Sep 11 '21 at 17:02
  • Done. Get: `Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at (index):1` – Oscar Sep 11 '21 at 17:06
  • button still have an id? – Kofusu Sep 11 '21 at 17:07
  • The script is on the header ok? – Oscar Sep 11 '21 at 17:07
  • `` – Oscar Sep 11 '21 at 17:08
  • have you try put script under the button? – Kofusu Sep 11 '21 at 17:08
  • I'm going to try it – Oscar Sep 11 '21 at 17:09
  • if use addEventlistener is good put script after the document – Kofusu Sep 11 '21 at 17:10
  • same error `Uncaught TypeError: Cannot read properties of null (reading 'addEventListener') at (index):1` – Oscar Sep 11 '21 at 17:11
  • its maybe because button not detected before script – Kofusu Sep 11 '21 at 17:14
  • [link](https://codepen.io/Thyrus/pen/vYZmzXP) i try it works – Kofusu Sep 11 '21 at 17:23
  • True, it works. It's the same as with your first code (it also worked in a simulator). It's weird. – Oscar Sep 11 '21 at 17:33
  • I think I've found the problem. https://stackoverflow.com/questions/51805395/navigator-clipboard-is-undefined. "This requires a secure origin — either HTTPS or localhost". The server where I need the button is a local server 192.168.4.1, so it's not https secure – Oscar Sep 11 '21 at 18:29