Skip to main content

JavaScript 剪貼簿複製操作

在瀏覽器中,將資料複製到剪貼簿的方法有三種:

  1. [ 棄用] Document.execCommand()copy 指令

  2. Clipboard API

  3. ClipboardEventcopypaste 事件

Document.execCommand

執行 document.execCommand('copy') 就可以將當前選取範圍複製到剪貼簿。

const btnCopy = document.querySelector('.btnCopy')
console.log(btnCopy)
btnCopy.addEventListener('click', function() {
document.execCommand('copy')
})

vue copy function demo

const copyLink = () => {
const linkText = 'text_link'
const tempInput = document.createElement("input");
tempInput.value = linkText;
document.body.appendChild(tempInput);
tempInput.select();
document.execCommand("copy");
document.body.removeChild(tempInput);
};

Clipboard API

1. Clipboard 物件

navigator.clipboard 會回傳 Clipboard 物件,所有操作都是透過它進行。

const cb = navigator.clipboard; `

navigator.clipboard 回傳 undefined,表示當前瀏覽器不支援。

2. 安全和權限

直接訪問剪貼簿的操作其實並不安全,因此 Clipboard API 僅支持通過 HTTPS 提供的頁面(開發環境 localhost 例外),且必須使用者授權才能訪問。

img

若是在 <iframe> 中運行,父頁面必須授予 clipboard-read(讀權限) 或 clipboard-write(寫權限)。

<iframe allow="clipboard-read; clipboard-write"></iframe>

另外,我們可以使用 Permissions APIPermissions.query() 查看是否有權訪問剪貼簿。

3. 操作方法

  • readText():讀取剪貼簿純文字內容。
  • writeText():對剪貼簿寫入純文字內容。
  • read():讀取剪貼簿複合內容。
  • write():對剪貼簿寫入複合內容。

以上方法皆會回傳一個 Promise 物件,讀取方法有結果值可以接收,若使用者拒絕授權,會拋出 NotAllowedError。

// 讀
navigator.clipboard.readText()
.then((text) => {
console.log(text);
})
.catch((err) => {
console.error(err);
});

// 寫

const text = 'Hello!';
navigator.clipboard.writeText(text)
.then(() => {
console.log('內容已複製');
})
.catch((err) => {
console.error(err);
});

也可以使用 async/await 語法:

async function readFromClipboard() {
try {
const text = await navigator.clipboard.readText();
console.log(text);
} catch (error) {
console.error(error);
}
}

async function writeToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('內容已複製');
} catch (error) {
console.error(error);
}
}

優缺點

優點:

  • 操作簡單,能直接訪問剪貼簿,不需要像 document.execCommand('copy') 需要有選取範圍才能使用。
  • 非同步操作。

缺點:

  • 需要使用者授權。

ClipboardEvent

ClipboardEvent 介面描述了與修改剪貼簿相關的事件。當使用者執行剪貼簿相關的操作,我們可以透過監聽 cutcopypaste,攔截事件以進行操作。

cutcopypaste 這些事件僅在當前頁面上操作時觸發。

這些事件的 event 物件中的 clipboardData 屬性 ,有三個方法可以使用:

  • clearData():清除剪貼簿資料,可指定資料類型,若不指定則清除全部。
  • getData():取得剪貼簿資料,需要指定資料類型。
  • setData():修改剪貼簿資料,需要指定資料類型。

1. 複製操作

當我們執行複製操作時,可以監聽 copy 事件,將指定內容放入剪貼簿。

document.addEventListener('copy', function(event) {
event.preventDefault();
event.clipboardData.setData('text/plain', 'Hello!');
});

我們有時候複製某些網站的內容時,會自動加上版權出處:

document.addEventListener('copy', function(event) {
const text = window.getSelection().toString();
if (text.length > 15) {
event.preventDefault();
event.clipboardData.setData('text/plain', '來源:竹白記事本\n' + text);
}
});

Clipboard.js

就是一個 npm

自己寫的一點點 demo

參考文章

https://chupai.github.io/posts/2101/clipboard/#clipboardevent