做前端時常會遇到「點一下把連結複製起來」的需求。這個功能看似簡單,但因為涉及剪貼簿權限,歷史上有過好幾代實作方式。本文先保留當時那個兼容 IE 與 Firefox 的經典寫法,再說明現在應該怎麼做。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript 複製功能,兼容多瀏覽器</title>
</head>
<script language="javascript">
copyValue = function (strValue) {
if (isIE()) {
clipboardData.setData("Text", strValue);
alert("您已成功復制了此地址");
} else {
copy(strValue);
alert("內容已被復制!");
}
}
function isIE(number) {
if (typeof(number) != number) { return !!document.all; }
}
function copy(text2copy) {
var flashcopier = 'flashcopier';
if (!document.getElementById(flashcopier)) {
var divholder = document.createElement('div');
divholder.id = flashcopier;
document.body.appendChild(divholder);
}
document.getElementById(flashcopier).innerHTML = '';
var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard=' + text2copy + '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
document.getElementById(flashcopier).innerHTML = divinfo;
}
</script>
<div class="phoinfo">
貼圖地址:
<input name="txtPhotoPath" value="www.daimajiayuan.com" id="txtPhotoPath" type="text" size="65" />
<input type="button" name="btnCopy" id="btnCopy" onClick="copyValue('www.daimajiayuan.com');" value="復制" />
</div>
</body>
</html>
Flash 已於 2020 年底正式停止支援,所有主流瀏覽器都移除了 Flash 執行環境,那段 <embed> 完全不會生效。IE 專用的 clipboardData 也只有舊 IE 能用。因此這份程式碼今天只剩下閱讀與考古價值。
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('複製成功');
} catch (err) {
console.error('複製失敗:', err);
}
}
使用前提:頁面必須在 HTTPS(或 localhost)環境下執行,而且呼叫必須發生在使用者互動(如點擊)的情境中,瀏覽器才會授權。
若需要支援較舊的 Safari 或非 HTTPS 環境,可以退回用隱藏的 textarea:
function copyByExecCommand(text) {
var textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
var ok = document.execCommand('copy');
document.body.removeChild(textarea);
return ok;
}
實務上常見的組合是「優先嘗試 Clipboard API,失敗時自動退回 execCommand」,這樣既乾淨又保有相容性。要注意的是 execCommand 已被標記為 deprecated,只是目前仍普遍可用,不宜作為長期唯一方案。