剪下及貼上文字是應用程式 (尤其是電腦應用程式) 最常用的功能之一。如何複製網頁上的文字?有舊方法和新方法。實際情況取決於使用的瀏覽器。
現代做法
使用 Async Clipboard API
Clipboard.writeText() 方法會接收字串,並傳回 Promise,在文字成功寫入剪貼簿時解析。Clipboard.writeText() 只能從具有焦點的 window 物件使用。
傳統做法
使用document.execCommand()
呼叫 document.execCommand('copy') 會傳回布林值,指出複製作業是否成功。在使用者手勢 (例如點擊處理常式) 內呼叫這項指令。相較於 Async Clipboard API,這種做法有其限制。execCommand() 方法僅適用於 DOM 元素。由於是同步作業,複製大量資料 (尤其是必須以某種方式轉換或清除的資料) 時,可能會導致網頁遭到封鎖。
漸進增強
const copyButton = document.querySelector('#copyButton');
const out = document.querySelector('#out');
if ('clipboard' in navigator) {
copyButton.addEventListener('click', () => {
navigator.clipboard.writeText(out.value)
.then(() => {
console.log('Text copied');
})
.catch((err) => console.error(err.name, err.message));
});
} else {
copyButton.addEventListener('click', () => {
const textArea = document.createElement('textarea');
textArea.value = out.value;
textArea.style.opacity = 0;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
const success = document.execCommand('copy');
console.log(`Text copy was ${success ? 'successful' : 'unsuccessful'}.`);
} catch (err) {
console.error(err.name, err.message);
}
document.body.removeChild(textArea);
});
}
延伸閱讀
- 解除封鎖剪貼簿存取權 (新方法)
- 剪下和複製指令 (傳統方式)
示範
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link
rel="icon"
href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎉</text></svg>"
/>
<title>How to copy text</title>
</head>
<body>
<h1>How to copy text</h1>
<textarea rows="3">
Some sample text for you to copy. Feel free to edit this.</textarea
>
<button type="button">Copy</button>
</body>
</html>CSS
:root {
color-scheme: dark light;
}
html {
box-sizing: border-box;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 1rem;
font-family: system-ui, sans-serif;
}
button {
display: block;
}
JS
const textarea = document.querySelector('textarea');
const button = document.querySelector('button');
button.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(textarea.value);
} catch (err) {
console.error(err.name, err.message);
}
});