Copy to clipboard doesn't work on Chrome in VueJS
Vinavi Anutara
In my VueJS app, I have a component that copies the base URL to the clipboard by clicking a link
<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>
I have the following method in my script,
copyURL() {
this.$refs.text.select();
document.execCommand("copy");
this.flash = "lien copié dans le presse-papiers";
},
This works fine on my Firefox browser, but on my Chrome this doesn't copy the link to the clipboard...
Volka Dimitrev
<a @click="copyURL" ref="mylink">
<img class="social_icon" src="/images/game/copy-fr.png" alt="Copy icon"
/></a>
Your method should be as 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 a different value instead of the base url then simply change
el.value = window.location.origin;
arrive
el.value = this.link_url;
or
el.value = "www.yourlink.com";