「點一下就複製」看起來是個小功能,在瀏覽器林立的年代卻讓無數前端頭疼過。這段歷史大致可以分成三個階段。
在 Flash 9 時期,有個幾乎通吃的方案:以一個名為 _clipboard.swf 的隱藏 Flash 檔作為橋樑,透過 FlashVars 把要複製的字串傳進去,由 Flash 寫入系統剪貼板。
var setcopy_gettext = function(){
clipboardswfdata = document.getElementById('test_text').value;
window.document.clipboardswf.SetVariable('str', clipboardswfdata);
};
它幾乎支援當時所有主流瀏覽器,可謂完美。
Flash 10 新增了一條安全限制:只有使用者對 SWF 進行真實操作(例如點擊)時,才允許存取剪貼板。純靠 JavaScript 遙控一個隱藏 SWF,不再被接受。
社群的解法相當巧妙:把一個透明的 Flash 物件疊在真正的 DOM 按鈕上,使用者以為自己點的是網頁按鈕,實際點擊落在 Flash 上,於是「真實操作」這個條件就被滿足了。Zero Clipboard 就是這個思路的成熟封裝。
var clip = null;
function $(id) { return document.getElementById(id); }
function init() {
clip = new ZeroClipboard.Client();
clip.setHandCursor(true);
clip.addEventListener('mouseOver', function () {
clip.setText($('fe_text').value); // 移入時更新要複製的內容
});
clip.addEventListener('complete', function (client, text) {
alert("該地址已經複製,你可以使用 Ctrl+V 粘貼。");
});
clip.glue('clip_button', 'clip_container'); // 把透明 Flash 黏到按鈕上
}
要注意的是,這個頁面必須透過 http 協定開啟,直接用檔案協定開啟會因權限問題失敗;moviePath 也必須指向正確的 SWF 位置。
Flash 已於 2020 年底正式停止支援,上面兩套方案如今都只能當歷史閱讀。現代做法有兩條路:
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('複製成功');
} catch (err) {
console.error('複製失敗', err);
}
}
它設計乾淨、基於 Promise,但必須在 HTTPS(或 localhost)環境下才能使用,且需要使用者授權。
function copyByExecCommand(text) {
var textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
var ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
}
navigator.clipboard,並用 try/catch 包住,因為使用者可能拒絕授權。execCommand。