Search code examples
vue.jsclipboard

Copy link value using navigator API is not working in Vue


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!");
},
  1. What is going on? Is it because of the http:// or https://?
  2. How it can be implemented that clicking on the link and getting the value copied to the clipboard?

Thanks in advance


Solution

  • What I tested-

    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>

    What is written in the documentation-

    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.

    What Github issue suggested-

    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.

    My suggestion-

    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-

    1. https://www.npmjs.com/package/clipboard
    2. https://www.npmjs.com/package/copy-to-clipboard
    3. https://www.npmjs.com/package/vue-clipboard2 (I am currently using this.)