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.
writeText es una función asíncrona, debe usar then para obtener el resultado.And Chrome has some limitations, you may see an error message if it crashes.
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 }) } <span id="pwd" onclick="copyPassword()">click me</span> <span id="msg">Respuesta</span>