DIV CSS 佈局教程網

複製到剪貼簿:IE 與 Chrome 的分歧處理
編輯:JavaScript綜合知識     

「點擊複製」是常見的小功能,但瀏覽器對剪貼簿的權限模型差異很大,過去往往需要為不同瀏覽器寫兩套程式。

IE:select 加 execCommand

舊版 IE 允許腳本直接操作剪貼簿,做法是先選取文字框內容,再執行瀏覽器的複製命令:

function copyUrl2() {
  var Url2 = document.getElementById("biao1");
  Url2.select();                    // 選取物件
  document.execCommand("Copy");     // 執行複製命令
  alert("已複製好,可貼粘。");
}
<textarea cols="20" rows="10" id="biao1">用戶定義的代碼區域</textarea>
<input type="button" onClick="copyUrl2()" value="點擊複制代碼" />

Chrome:Flash 時期的 ZeroClipboard

當時 Chrome 基於安全性不開放 execCommand 的剪貼簿寫入,社群普遍用 ZeroClipboard 這類以 Flash 為媒介的方案繞過:

<script src="assets/js/copy/ZeroClipboard.js"></script>
<script type="text/javascript">
  var clip = new ZeroClipboard.Client();
  clip.setHandCursor(true);
  clip.setText('復制內容');
  clip.glue('button');
</script>

<input type="button" id="button" value="點擊復制代碼" />

現在怎麼寫才對

Flash 早已停用,ZeroClipboard 的這條路已經走不通。目前標準做法是 navigator.clipboard.writeText(),它基於 HTTPS 與使用者手勢授權,寫法一致且不需外接任何套件:

async function copyText(text) {
  try {
    await navigator.clipboard.writeText(text);
    alert('已複製');
  } catch (e) {
    // 舊瀏覽器或不安全環境下的退路
    var ta = document.getElementById("biao1");
    ta.select();
    document.execCommand("Copy");
  }
}

execCommand 雖已標記為不建議使用,但作為非 HTTPS 環境或舊瀏覽器的退路仍相當實用,因此以 clipboard API 為主、execCommand 為輔的漸進增強寫法,是目前最穩定的組合。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved