Sometimes, we want to copy to clipboard using JavaScript in iOS.
In this article, we’ll look at how to copy to clipboard using JavaScript in iOS.
How to copy to clipboard using JavaScript in iOS?
To copy to clipboard using JavaScript in iOS, we use the input.setSelectionRange
method.
For instance, we write
const copyText = (input) => {
const isIOSDevice = navigator.userAgent.match(/ipad|iphone/i);
if (isIOSDevice) {
input.setSelectionRange(0, input.value.length);
} else {
input.select();
}
document.execCommand("copy");
};
to define the copyText
function.
In it, we check if the function is run on an iOS device by checking the user agent with navigator.userAgent
.
We check if 'iPad'
or 'iPhone'
is in the user agent string.
If it is, we call input.setSelectionRange
to select the input’s text.
Otherwise, we use input.select
to do the same thing.
Then we call document.execCommand
with 'copy'
to copy the selected text to the clipboard.
Conclusion
To copy to clipboard using JavaScript in iOS, we use the input.setSelectionRange
method.