「點一下把網址複製好」是很多分享功能的收尾步驟。在 Flash 還沒退場的年代,跨瀏覽器複製幾乎只能靠它;如今則有標準的 Clipboard API 可用。以下先保留當年的經典寫法作為技術回顧,再談現在該怎麼做。
<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="https://files.jb51.net/demoimg/200910/_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>
IE 提供了 clipboardData.setData() 這個私有 API,能在使用者點擊的同步流程中寫入剪貼簿;其他瀏覽器則一律基於安全理由不開放。於是開發者想到一個折衷:動態插入一個寬高為 0 的 Flash embed,把要複製的內容放在 FlashVars 傳進去,由 Flash 執行寫入。由於必須在點擊事件內同步建立,稍一延後就會失效,這也是為何程式碼看起來如此迂回。
Flash 已於 2020 年底停止支援,上述方案今日完全不可用;IE 的 clipboardData 也不再需要考慮。標準做法如下:
async function copyText(text) { try { await navigator.clipboard.writeText(text); console.log('複製成功'); } catch (err) { console.warn('瀏覽器未授予權限或家长们非安全內容', err); } }
使用上有兩個前提:頁面必須在 HTTPS 或 localhost 的安全環境下執行,且呼叫需發生於使用者手勢(如點擊)的同步流程中。若需讀取剪貼簿,則是 navigator.clipboard.readText(),通常還會跳出權限請求。
萬一仍要支援沒有 Clipboard API 的環境,實務上會退到 hidden textarea + document.execCommand('copy') 的組合:建立一個臨時 textarea、把文字放進去、選取它,再呼叫 execCommand,最後移除元素。這個方法已被標記為不建議使用,但在舊版 Safari 上偶爾仍是唯一可行的路。記得任何 fallback 都要保留 try/catch,並在失敗時讓使用者手動選取文字作為最後手段。