K. D.
K. D.

Reputation: 4219

Use navigator.clipboard combined with asynchronous requests

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

Upvotes: 1

Views: 843

Answers (1)

Jacob
Jacob

Reputation: 624

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.

Upvotes: 1

Related Questions