萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 複製文字到剪貼簿(跨瀏覽器兼容方案)

剪貼簿 API 歷經 document.execCommand('copy') 到現代 navigator.clipboard.writeText(),本文提供兼容 IE、Firefox、Chrome 的漸進式封裝。

現代標準 API(HTTPS + 用戶手勢)

async function copyModern(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (e) { return false; }
}

降級方案:execCommand(廣泛支援,但已棄用)

function copyLegacy(text) {
  var ta = document.createElement('textarea');
  ta.value = text;
  ta.style.position = 'fixed';
  ta.style.opacity = 0;
  document.body.appendChild(ta);
  ta.select();
  try {
    return document.execCommand('copy');
  } finally {
    document.body.removeChild(ta);
  }
}

統一封裝

function copyToClipboard(text) {
  if (navigator.clipboard && window.isSecureContext) {
    return navigator.clipboard.writeText(text);
  }
  return new Promise(function(resolve) {
    resolve(copyLegacy(text));
  });
}

// 使用
btn.addEventListener('click', function() {
  copyToClipboard('要複製的內容').then(function(ok) {
    alert(ok ? '複製成功' : '複製失敗,請手動 Ctrl+C');
  });
});

舊版 Firefox 特殊處理(已極少見)

早期 Firefox 需 netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect'),現代版本已移除,無需處理。

注意

  • 現代 API 需**安全上下文**(HTTPS 或 localhost)且由**用戶手勢觸發**(click、keydown 等)。
  • execCommand 在部分瀏覽器需元素可見且可選取,故用 textarea 臨時承載。
copyright © 萬盛學電腦網 all rights reserved