In a vue.js app, I want to click on a link and copy its value to the clipboard but each time I clicked I got this error-
[Vue warn]: Error in v-on handler (Promise/async): "TypeError: navigator.clipboard is undefined"
Here is my code-
<a @click.prevent="copyEmailLink" href="#" ref="emailLink">[email protected]</a>
async copyEmailLink() {
console.log(this.$refs.emailLink.textContent)
await navigator.clipboard.writeText(this.$ref.emailLink.textContent);
await alert("Copied!");
},
Thanks in advance
After reproducing your example, I didn't receive the warning message like yours but received another error message. If you will run the below demo (which is one of the correct ways to use the navigator clipboard API), you should see an error like this-
The Clipboard API has been blocked because of a permissions policy applied to the current document.
new Vue({
el: "#app",
methods: {
copyEmailLink() {
navigator.clipboard.writeText(this.$refs.emailLink.textContent).then(function() {
console.log('Copied!');
}, function(e) {
console.log(e.message)
});
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<a @click.prevent="copyEmailLink" href="#" ref="emailLink">[email protected]</a>
</div>
After giving a read to the documentation, I found this-
Use of the asynchronous clipboard read and write methods requires that the user grant the website or app permission to access the clipboard. This permission must be obtained from the Permissions API using the "clipboard-read" and/or "clipboard-write" permissions.
I also found a related GitHub issue which suggests-
You can use
Document.execCommand()
but as this is deprecated and really anything that's being written today should be using the much better clipboard API.
There are so many NPM packages that can do this job very easily. So, instead of using this navigator API, you can try one of those NPM clipboard packages.
Here are a few-