要複製頁面上的內容,我們可以使用 exeCommand('copy'),但首先要複製的內容需要存在頁面上,可以參考以下寫法:
var copyText = document.getElementById("input");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /*For mobile devices*/
/* Copy the text inside the text field */
document.execCommand("copy");
那如果想要複製的內容不在頁面上,可能是靠程式產生的或是網址之類的,就必須先產生一個 html 元素,在複製後馬上刪掉即可:
var dummy = document.createElement('input'),
text = window.location.href;
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand('copy');
document.body.removeChild(dummy);
參考:
How TO - Copy Text to Clipboard
Copy current URL to clipboard