這個範例示範如何用 JavaScript 把輸入框裡的文字寫進剪貼簿,以及把剪貼簿的內容讀回來。介面只有一個文字框和兩個按鈕,卻涵蓋了剪貼簿操作最關鍵的三個步驟。
<script language="javascript">
function readTxt() {
alert(window.clipboardData.getData("text"));
}
function setTxt() {
var t = document.getElementById("txt");
t.select();
window.clipboardData.setData('text', t.createTextRange().text);
}
</script>
<input name="txt" value="測試">
<input type="button" value="復制" onclick="setTxt()">
<input type="button" value="讀取" onclick="readTxt()">
setTxt 觸發時,先用 select() 把輸入框內容全選,再透過 createTextRange().text 取出這段選文中的純文字,最後交給 setData('text', ...) 寫入剪貼簿。readTxt 則是反過來,用 getData('text') 取出剪貼簿裡的純文字並跳出提示。
這段程式依賴 window.clipboardData,而它是 IE 的私有實作,在 Chrome、Firefox、Safari 上會直接丟出 undefined 錯誤。此外,基於安全考量,IE 預設會攔截網頁存取剪貼簿的行為,執行時可能出現安全性提示,需要手動允許。
// 寫入:讀取輸入框的值,直接送進剪貼簿
document.getElementById("copyBtn").addEventListener("click", function () {
var value = document.getElementById("txt").value;
navigator.clipboard.writeText(value)
.then(function(){ alert("已複製"); })
.catch(function(){ alert("複製失敗,請檢查權限"); });
});
// 讀取:需要使用者授權
document.getElementById("readBtn").addEventListener("click", function () {
navigator.clipboard.readText()
.then(function(text){ alert(text); })
.catch(function(){ alert("無法讀取剪貼簿"); });
});
這個版本的好處是不必再手動選取文字,也不必自己處理 textRange;代價是必須在 HTTPS 環境下執行,且讀取動作會觸發權限請求。
實務上還有一個常見技巧,是把要複製的字串放進一個臨時 textarea、選取後呼叫 document.execCommand('copy'),這種寫法相容性最好,至今仍被大量函式庫採用。