How to copy some text into Clipboard with JavaScript within WKWebView? Sounds easy, there are however some gotchas one should know about:
- The “new” navigator.clipboard API call is asynchronous, i.e. you get a Promise object as a result:
function copyToClipboard() {
navigator.clipboard.writeText("Some text to copy").then(function() {
alert('success!');
}, function(error) {
alert('failed with error: ' + error);
});
}
- Important note from documentation : The implementation is available through the
navigator.clipboard
API which must be called within user gesture event handlers likepointerdown
orpointerup
, and only works for content served in a secure context (e.g.https://
)
This means in particular, you cannot just call navigator.clipboard.writeText where ever you want, but rather within an onClick handler, e.g.
<button name="some name" onclick="copyToClipboard();">Click me</button>
The navigator.clipboard
API is supported starting with Safari 13.1