Issue
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 on PC but not 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
Solution
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
Answered By - Agil Atakishiyev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.