1

I want to use navigator.clipboard.writeText to copy a link to the clipboard. However, this link must be generated by the server, which is why copying is preceded by a fetch.

Sample code:

<button onclick="onClick()">Copy</button>

<script>

    function onClick() {
        fetchLink()
            .then(function (link) {
                navigator.clipboard.writeText(link);
                alert('Copy ok');
            })
            .catch(function (err) {
                alert('Error: ' + err.message);
            })
    }
</script>

For this reason, copying does not currently seem to work, especially under iOS, since the function is not called directly by the user in an event handler.

How could I solve this problem?

Many Thanks

K. D.
  • 3,271
  • 7
  • 30
  • 57
  • Possible solutions to write on the clipboard. https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript?rq=1 – tsfahmad Jan 15 '21 at 12:09

1 Answers1

1

While not being a cross-browser solution, you could potentially use the Permissions API to request access to the clipboard without requiring a user gesture to initiate it. Something like this:

const queryOpts = { name: 'clipboard-write', allowWithoutGesture: false };
const permissionStatus = await navigator.permissions.query(queryOpts);

The downside of this approach is, like I said, it's not cross-browser (read: Safari does not support this). Also, it pops up a permission notification which the user may not accept.

If this doesn't work for you, I don't think there's a way to work around this. I would suggest, that depending on your UI, you may want to change it to a button that says "Generate Link" and then after the fetch it would display the link with a copy button, but that's out of the scope for this question.

Jacob
  • 392
  • 2
  • 12
  • 1
    Is should ask for `clipboard-write` though, right? They want to get the URL _into_ the clipboard, not read from it. – CBroe Jan 15 '21 at 11:31