舊式寫法使用 `document.execCommand('copy')` 已棄用。現代瀏覽器支援 **Clipboard API** (`navigator.clipboard.writeText()`),安全、非同步、需 HTTPS 或 localhost。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>表單提交自動複製到剪貼板</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
textarea { width: 100%; min-height: 120px; font-family: inherit; font-size: 1rem; }
.checkbox-group { margin: 1rem 0; }
button { padding: 0.75rem 1.5rem; font-size: 1rem; cursor: pointer; }
.toast { position: fixed; bottom: 1rem; right: 1rem; background: #333; color: #fff; padding: 0.75rem 1.5rem; border-radius: 4px; opacity: 0; transition: opacity 0.3s; pointer-events: none; }
.toast.show { opacity: 1; }
</style>
</head>
<body>
<h1>表單提交自動複製示範</h1>
<form id="demoForm">
<textarea id="content" name="content" placeholder="輸入要複製的內容..."></textarea>
<div class="checkbox-group">
<label><input type="checkbox" id="autoCopy" checked> 提交時自動複製到剪貼板</label>
</div>
<button type="submit">提交</button>
</form>
<div id="toast" class="toast">已複製到剪貼板!</div>
<script>
const form = document.getElementById('demoForm');
const contentEl = document.getElementById('content');
const autoCopyEl = document.getElementById('autoCopy');
const toast = document.getElementById('toast');
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showToast('已複製到剪貼板!');
return true;
} catch (err) {
console.error('複製失敗:', err);
showToast('複製失敗:' + err.message, true);
return false;
}
}
function showToast(message, isError = false) {
toast.textContent = message;
toast.style.background = isError ? '#c00' : '#333';
toast.classList.add('show');
setTimeout(() => toast.classList.remove('show'), 2000);
}
form.addEventListener('submit', async (e) => {
e.preventDefault(); // 示範用,實際提交請移除
const text = contentEl.value;
if (!text.trim()) {
showToast('內容不可為空', true);
return;
}
if (autoCopyEl.checked) {
await copyToClipboard(text);
}
// 實際提交邏輯:fetch('/api/submit', { method: 'POST', body: new FormData(form) })
console.log('表單提交:', { content: text, autoCopy: autoCopyEl.checked });
showToast('表單已提交 (示範模式)');
});
</script>
</body>
</html>
| 項目 | 說明 |
|---|---|
| HTTPS 必須 | Clipboard API 僅在安全上下文 (HTTPS、localhost) 可用 |
| 使用者互動觸發 | 必須在使用者主動事件 (click, submit) 中呼叫,否則拋出 `NotAllowedError` |
| 非同步 Promise | `navigator.clipboard.writeText()` 回傳 Promise,需 `await` 或 `.then()` |
| 權限政策 | 可透過 Permissions Policy `` 控制 |
<?php
// 僅在不支援 Clipboard API 時載入
?>
<script>
if (!navigator.clipboard) {
navigator.clipboard = {
writeText: function(text) {
return new Promise((resolve, reject) => {
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
const successful = document.execCommand('copy');
successful ? resolve() : reject(new Error('execCommand copy failed'));
} catch (err) {
reject(err);
} finally {
document.body.removeChild(textarea);
}
});
}
};
}
</script>
<?php
// submit.php
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Method not allowed']);
exit;
}
$content = trim($_POST['content'] ?? '');
if ($content === '') {
http_response_code(400);
echo json_encode(['error' => 'Content required']);
exit;
}
// 處理業務邏輯:存資料庫、發通知...
// $pdo->prepare('INSERT INTO logs (content) VALUES (?)')->execute([$content]);
echo json_encode(['success' => true, 'message' => '已接收']);
現代 Clipboard API 取代了脆弱的 `execCommand`,提供更安全、標準的剪貼板存取。結合表單提交事件,即可實作「一鍵複製並送出」的優質使用者體驗。記得處理權限拒絕、HTTPS 需求與舊瀏覽器相容。