Copying value of <p> element to clipboard using Javascript

Viewed 61

I'm working on a password generator which generates a random passwords and displays inside a <p> element. That part works fine.

I want to copy the output value (generated password) in the <p> element to the clipboard when the user clicks on the password value in <p>

Here's my code:

function copyPassword() {

    let password = document.getElementById("pwd").innerText
    let message = document.getElementById("msg")

    //This doesn't seem to work
    navigator.clipboard.writeText(password) 

    //This works
    message.innerText = "Copied to clipboard"
}
<p id="pwd" onclick="copyPassword()">click me</p>
<p id="msg"></p>

UPDATE: I just checked in Firefox; this code seems to work perfectly. But it doesn't on Chrome, Edge and Safari.

UPDATE 2: I uploaded the files to a GitHub repo and published. Works just fine. So no issues with the code.

1 Answers

writeText is an async function, you should use then to get the result.

And chrome has some limitations for it, you can see error message if it failed.

function copyPassword() {

    let password = document.getElementById("pwd").innerText
    let message = document.getElementById("msg")

    //This doesn't seem to work
    navigator.clipboard.writeText(password)
      .then(() => {
        //This works
        message.innerText = "Copied to clipboard"
      })
      .catch((err) => {
        message.innerText = err.message
      })

    
}
<p id="pwd" onclick="copyPassword()">click me</p>
<p id="msg"></p>

Related