برای اینکه متنی رو توی حافظه کپی کنین کافیه متنشتون رو به تابع زیر ارسال کنین:
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
تابع بالا از فیلد input استفاده میکنه که ممکنه واسه همه جالب نباشه و بکارمون نیاد. من خودم بعد کمی تست و گشتن به این نتیجه رسیدم که از clipboardjs (این کتابخونه هم خوبه: https://clipboardjs.com) استفاده کنم. متاسفانه کد من با این کتابخونه تداخل داشته و ناچارا رفتم سراغ جستجو و کد زیر رو پیدا کردم که بسیار هم عالی بود.
function copyLink(containerid) {
var elm = document.getElementById(containerid);
// for Internet Explorer
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(elm);
range.select();
document.execCommand("Copy");
alert("Copied div content to clipboard");
}
else if (window.getSelection) {
// other browsers
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(elm);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
alert("Copied div content to clipboard");
}
}
منبع:
How TO – Copy Text to Clipboard
How to copy the div content to Clipboard
