Home > front end >  why does navigator.clipboard.writeText doesn't copy text to clipboard if it was proceeded by al
why does navigator.clipboard.writeText doesn't copy text to clipboard if it was proceeded by al

Time:10-05

when trying to copy some text on chrome for android with navigator.clipboard.writeText() it works as long as I don't show an alert afterwards . the moment I show an alert() it doesn't work anymore For example this works fine as intended

function myFunction() {
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
}
<input type="text" value="Hello world" id="myInput" style="width:auto">
<button onclick="myFunction()">copy</button>

However this doesn't work , it doesn't throw any errors in the console and works fine on chrome for the computer but not on chrome for android

function myFunction() 
{
  var copyText = document.getElementById("myInput");
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  navigator.clipboard.writeText(copyText.value);
  alert("Successfully copied the text")
}
<input type="text" value="Hello world" id="myInput"  style="width:auto" >
<button onclick="myFunction()" >copy</button>

anyone knows what is going on ?! . Thanks

CodePudding user response:

Because navigator.clipboard.writeText method returns a promise and you are not waiting for its results, if you correct code like below that would be fine:

function myFunction() {
    var copyText = document.getElementById("myInput");
    copyText.select();
    copyText.setSelectionRange(0, 99999);
    navigator.clipboard
      .writeText(copyText.value)
      .then(() => {
        alert("successfully copied");
      })
      .catch(() => {
        alert("something went wrong");
      });
}

Also for further information about Promise and navigator.clipboard.writeText methods please visit the links below:
Link 1
Link 2
Link 3

CodePudding user response:

try this:

<input type="text" value="Hello world" id="myInput"  style="width:auto" >
    <button onclick="myFunction()" id="btn">copy</button>

    <script>
        let submit = document.getElementById("btn")

submit.addEventListener('click', function(){
    var copyText = document.getElementById("myInput");

  copyText.select();
  copyText.setSelectionRange(0, 99999);

  navigator.clipboard.writeText(copyText.value);
  
  alert("Copied the text: "   copyText.value);

})
    </script>

  • Related