como habrás adivinado por mi pregunta y como interpretarás mirando mi código, soy un principiante. esta es la primera aplicación real que traté de escribir en javascript y me encantaría entender por qué no funciona.
var button = document.getElementById("button"); var text = document.getElementById("text"); function button() { text.select(); text.setSelectionRange(0, 99999); navigator.clipboard.writeText(text.value); alert("you copied this text"); }el botón es un evento onclick en html y el texto es una entrada en html. Muchísimas gracias
Como se mencionó, writeText es una promesa, pero también la Clipboard API necesita permiso. Marque esto si el permiso se concede o no
function myFunction() { /* Get the text field */ var copyText = document.getElementById("myText"); /* 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).then(function() { alert("Copied to clipboard successfully!"); }, function(error) { alert("ERROR:\n"+error); });; } async function CheckPermission(){ const readPerm = await navigator.permissions.query({name: 'clipboard-read', allowWithoutGesture: false }); const writePerm = await navigator.permissions.query({name: 'clipboard-write', allowWithoutGesture: false }); // Will be 'granted', 'denied' or 'prompt': alert('Read: '+readPerm.state+'\nWrite: '+writePerm.state); } <input type="text" value="ASDF" id="myText"> <button onclick="myFunction()">Copy text</button><br><br> <button onclick="CheckPermission()">Check Permission</button>Si es así, necesita pedir permiso. Más información aquí .
No sé si debería escribir esto como una respuesta o qué. pero de todos modos reescribí el código y terminó así:
var text = document.getElementById("text"); var button = document.getElementById("button"); function buttonholder() { text.select(); text.setSelectionRange(0, 99999) navigator.clipboard.writeText(text.value); } button.addEventListener("click",buttonholder);gracias a todos los que respondieron. funciona bien. No sé por qué el primer código no funcionó, pero bueno, el segundo código es mucho mejor que el último, gracias por ayudar. algunas de sus referencias me hicieron pensar en addEventListener.