Home > Software engineering >  Copy to clipboard not working on Chrome browser in VueJS
Copy to clipboard not working on Chrome browser in VueJS

Time:09-28

In my VueJS application, I have a component to copy the base URL to the clipboard on a link click

<a @click="copyURL" ref="mylink">
            <img class="social_icon" src="/images/game/copy-fr.png" alt="Copy icon"
          /></a>
          <input type="text" class="copyurl_txt" v-model="base" ref="text" />
          <div v-if="flash" v-text="flash"></div>

And I have following method inside my script,

copyURL() {
      this.$refs.text.select();
      document.execCommand("copy");
      this.flash = "lien copié dans le presse-papiers";
    },

This works well on my Firefox browser, but on my Chrome this not copying the link to the clipboard...

CodePudding user response:

<a @click="copyURL" ref="mylink">
            <img class="social_icon" src="/images/game/copy-fr.png" alt="Copy icon"
          /></a>

And your method should like follows,

copyURL() {
            const el = document.createElement('textarea');  
            el.value = window.location.origin;                                 
            el.setAttribute('readonly', '');                
            el.style.position = 'absolute';                     
            el.style.left = '-9999px';                      
            document.body.appendChild(el);                  
            const selected =  document.getSelection().rangeCount > 0  ? document.getSelection().getRangeAt(0) : false;                                    
            el.select();                                    
            document.execCommand('copy');                   
            document.body.removeChild(el);                  
            if (selected) {                                 
              document.getSelection().removeAllRanges();    
              document.getSelection().addRange(selected);   
            }
            this.flash = "lien copié dans le presse-papiers";
        },

If you want to use different value instead of base url then simple change

el.value = window.location.origin;

to

el.value = this.link_url; 

or

el.value = "www.yourlink.com";

CodePudding user response:

That's because the input value isn't selectable in the same manner. This is probably one of those quirks that is handled differently by each browser. That happens. My advice is to not try and re-invent the wheel here. I've built a custom JS class just for copying text that works with all major browsers, including IE11, but it was a terrible job to do. I can't even share it due to copyright issues.

So just use a package like https://github.com/Inndy/vue-clipboard2 and be done with it.

If that's not an option, you have to look into creating a virtual DOM at runtime with an invisible table that you can then select and copy automatically.

  • Related