JS如何使用剪貼板操作Clipboard API
Document.execCommand()是操作剪貼板的傳統(tǒng)方法,各種瀏覽器都支持。
它支持復(fù)制、剪切和粘貼這三個(gè)操作。
document.execCommand(’copy’)(復(fù)制) document.execCommand(’cut’)(剪切) document.execCommand(’paste’)(粘貼)(1)復(fù)制操作復(fù)制時(shí),先選中文本,然后調(diào)用document.execCommand(’copy’),選中的文本就會(huì)進(jìn)入剪貼板。
const inputElement = document.querySelector(’#input’);inputElement.select();document.execCommand(’copy’);
上面示例中,腳本先選中輸入框inputElement里面的文字(inputElement.select()),然后document.execCommand(’copy’)將其復(fù)制到剪貼板。
注意,復(fù)制操作最好放在事件監(jiān)聽(tīng)函數(shù)里面,由用戶(hù)觸發(fā)(比如用戶(hù)點(diǎn)擊按鈕)。如果腳本自主執(zhí)行,某些瀏覽器可能會(huì)報(bào)錯(cuò)。
(2)粘貼操作粘貼時(shí),調(diào)用document.execCommand(’paste’),就會(huì)將剪貼板里面的內(nèi)容,輸出到當(dāng)前的焦點(diǎn)元素中。
const pasteText = document.querySelector(’#output’);pasteText.focus();document.execCommand(’paste’);(3)缺點(diǎn)
Document.execCommand()方法雖然方便,但是有一些缺點(diǎn)。
首先,它只能將選中的內(nèi)容復(fù)制到剪貼板,無(wú)法向剪貼板任意寫(xiě)入內(nèi)容。
其次,它是同步操作,如果復(fù)制/粘貼大量數(shù)據(jù),頁(yè)面會(huì)出現(xiàn)卡頓。有些瀏覽器還會(huì)跳出提示框,要求用戶(hù)許可,這時(shí)在用戶(hù)做出選擇前,頁(yè)面會(huì)失去響應(yīng)。
為了解決這些問(wèn)題,瀏覽器廠商提出了異步的 Clipboard API。
二、異步 Clipboard APIClipboard API 是下一代的剪貼板操作方法,比傳統(tǒng)的document.execCommand()方法更強(qiáng)大、更合理。
它的所有操作都是異步的,返回 Promise 對(duì)象,不會(huì)造成頁(yè)面卡頓。而且,它可以將任意內(nèi)容(比如圖片)放入剪貼板。
navigator.clipboard屬性返回 Clipboard 對(duì)象,所有操作都通過(guò)這個(gè)對(duì)象進(jìn)行。
const clipboardObj = navigator.clipboard;
如果navigator.clipboard屬性返回undefined,就說(shuō)明當(dāng)前瀏覽器不支持這個(gè) API。
由于用戶(hù)可能把敏感數(shù)據(jù)(比如密碼)放在剪貼板,允許腳本任意讀取會(huì)產(chǎn)生安全風(fēng)險(xiǎn),所以這個(gè) API 的安全限制比較多。
首先,Chrome 瀏覽器規(guī)定,只有 HTTPS 協(xié)議的頁(yè)面才能使用這個(gè) API。不過(guò),開(kāi)發(fā)環(huán)境(localhost)允許使用非加密協(xié)議。
其次,調(diào)用時(shí)需要明確獲得用戶(hù)的許可。權(quán)限的具體實(shí)現(xiàn)使用了 Permissions API,跟剪貼板相關(guān)的有兩個(gè)權(quán)限:clipboard-write(寫(xiě)權(quán)限)和clipboard-read(讀權(quán)限)。'寫(xiě)權(quán)限'自動(dòng)授予腳本,而'讀權(quán)限'必須用戶(hù)明確同意給予。也就是說(shuō),寫(xiě)入剪貼板,腳本可以自動(dòng)完成,但是讀取剪貼板時(shí),瀏覽器會(huì)彈出一個(gè)對(duì)話框,詢(xún)問(wèn)用戶(hù)是否同意讀取。
另外,需要注意的是,腳本讀取的總是當(dāng)前頁(yè)面的剪貼板。這帶來(lái)的一個(gè)問(wèn)題是,如果把相關(guān)的代碼粘貼到開(kāi)發(fā)者工具中直接運(yùn)行,可能會(huì)報(bào)錯(cuò),因?yàn)檫@時(shí)的當(dāng)前頁(yè)面是開(kāi)發(fā)者工具的窗口,而不是網(wǎng)頁(yè)頁(yè)面。
(async () => { const text = await navigator.clipboard.readText(); console.log(text);})();
如果你把上面的代碼,粘貼到開(kāi)發(fā)者工具里面運(yùn)行,就會(huì)報(bào)錯(cuò)。因?yàn)榇a運(yùn)行的時(shí)候,開(kāi)發(fā)者工具窗口是當(dāng)前頁(yè),這個(gè)頁(yè)面不存在 Clipboard API 依賴(lài)的 DOM 接口。一個(gè)解決方法就是,相關(guān)代碼放到setTimeout()里面延遲運(yùn)行,在調(diào)用函數(shù)之前快速點(diǎn)擊瀏覽器的頁(yè)面窗口,將其變成當(dāng)前頁(yè)。
setTimeout(async () => { const text = await navigator.clipboard.readText(); console.log(text);}, 2000);
上面代碼粘貼到開(kāi)發(fā)者工具運(yùn)行后,快速點(diǎn)擊一下網(wǎng)頁(yè)的頁(yè)面窗口,使其變?yōu)楫?dāng)前頁(yè),這樣就不會(huì)報(bào)錯(cuò)了。
三、Clipboard 對(duì)象Clipboard 對(duì)象提供了四個(gè)方法,用來(lái)讀寫(xiě)剪貼板。它們都是異步方法,返回 Promise 對(duì)象。
3.1 Clipboard.readText()Clipboard.readText()方法用于復(fù)制剪貼板里面的文本數(shù)據(jù)。
document.body.addEventListener( ’click’, async (e) => { const text = await navigator.clipboard.readText(); console.log(text); })
上面示例中,用戶(hù)點(diǎn)擊頁(yè)面后,就會(huì)輸出剪貼板里面的文本。注意,瀏覽器這時(shí)會(huì)跳出一個(gè)對(duì)話框,詢(xún)問(wèn)用戶(hù)是否同意腳本讀取剪貼板。
如果用戶(hù)不同意,腳本就會(huì)報(bào)錯(cuò)。這時(shí),可以使用try...catch結(jié)構(gòu),處理報(bào)錯(cuò)。
async function getClipboardContents() { try { const text = await navigator.clipboard.readText(); console.log(’Pasted content: ’, text); } catch (err) { console.error(’Failed to read clipboard contents: ’, err); }}3.2 Clipboard.read()
Clipboard.read()方法用于復(fù)制剪貼板里面的數(shù)據(jù),可以是文本數(shù)據(jù),也可以是二進(jìn)制數(shù)據(jù)(比如圖片)。該方法需要用戶(hù)明確給予許可。
該方法返回一個(gè) Promise 對(duì)象。一旦該對(duì)象的狀態(tài)變?yōu)?resolved,就可以獲得一個(gè)數(shù)組,每個(gè)數(shù)組成員都是 ClipboardItem 對(duì)象的實(shí)例。
async function getClipboardContents() { try { const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) {const blob = await clipboardItem.getType(type);console.log(URL.createObjectURL(blob)); } } } catch (err) { console.error(err.name, err.message); }}
ClipboardItem 對(duì)象表示一個(gè)單獨(dú)的剪貼項(xiàng),每個(gè)剪貼項(xiàng)都擁有ClipboardItem.types屬性和ClipboardItem.getType()方法。
ClipboardItem.types屬性返回一個(gè)數(shù)組,里面的成員是該剪貼項(xiàng)可用的 MIME 類(lèi)型,比如某個(gè)剪貼項(xiàng)可以用 HTML 格式粘貼,也可以用純文本格式粘貼,那么它就有兩個(gè) MIME 類(lèi)型(text/html和text/plain)。
ClipboardItem.getType(type)方法用于讀取剪貼項(xiàng)的數(shù)據(jù),返回一個(gè) Promise 對(duì)象。該方法接受剪貼項(xiàng)的 MIME 類(lèi)型作為參數(shù),返回該類(lèi)型的數(shù)據(jù),該參數(shù)是必需的,否則會(huì)報(bào)錯(cuò)。
3.3 Clipboard.writeText()Clipboard.writeText()方法用于將文本內(nèi)容寫(xiě)入剪貼板。
document.body.addEventListener( ’click’, async (e) => { await navigator.clipboard.writeText(’Yo’) })
上面示例是用戶(hù)在網(wǎng)頁(yè)點(diǎn)擊后,腳本向剪貼板寫(xiě)入文本數(shù)據(jù)。
該方法不需要用戶(hù)許可,但是最好也放在try...catch里面防止報(bào)錯(cuò)。
async function copyPageUrl() { try { await navigator.clipboard.writeText(location.href); console.log(’Page URL copied to clipboard’); } catch (err) { console.error(’Failed to copy: ’, err); }}3.4 Clipboard.write()
Clipboard.write()方法用于將任意數(shù)據(jù)寫(xiě)入剪貼板,可以是文本數(shù)據(jù),也可以是二進(jìn)制數(shù)據(jù)。
該方法接受一個(gè) ClipboardItem 實(shí)例作為參數(shù),表示寫(xiě)入剪貼板的數(shù)據(jù)。
try { const imgURL = ’https://dummyimage.com/300.png’; const data = await fetch(imgURL); const blob = await data.blob(); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }) ]); console.log(’Image copied.’);} catch (err) { console.error(err.name, err.message);}
上面示例中,腳本向剪貼板寫(xiě)入了一張圖片。注意,Chrome 瀏覽器目前只支持寫(xiě)入 PNG 格式的圖片。
ClipboardItem()是瀏覽器原生提供的構(gòu)造函數(shù),用來(lái)生成ClipboardItem實(shí)例,它接受一個(gè)對(duì)象作為參數(shù),該對(duì)象的鍵名是數(shù)據(jù)的 MIME 類(lèi)型,鍵值就是數(shù)據(jù)本身。
下面的例子是將同一個(gè)剪貼項(xiàng)的多種格式的值,寫(xiě)入剪貼板,一種是文本數(shù)據(jù),另一種是二進(jìn)制數(shù)據(jù),供不同的場(chǎng)合粘貼使用。
function copy() { const image = await fetch(’kitten.png’); const text = new Blob([’Cute sleeping kitten’], {type: ’text/plain’}); const item = new ClipboardItem({ ’text/plain’: text, ’image/png’: image }); await navigator.clipboard.write([item]);}四、copy 事件,cut 事件
用戶(hù)向剪貼板放入數(shù)據(jù)時(shí),將觸發(fā)copy事件。
下面的示例是將用戶(hù)放入剪貼板的文本,轉(zhuǎn)為大寫(xiě)。
const source = document.querySelector(’.source’);source.addEventListener(’copy’, (event) => { const selection = document.getSelection(); event.clipboardData.setData(’text/plain’, selection.toString().toUpperCase()); event.preventDefault();});
上面示例中,事件對(duì)象的clipboardData屬性包含了剪貼板數(shù)據(jù)。它是一個(gè)對(duì)象,有以下屬性和方法。
Event.clipboardData.setData(type, data):修改剪貼板數(shù)據(jù),需要指定數(shù)據(jù)類(lèi)型。 Event.clipboardData.getData(type):獲取剪貼板數(shù)據(jù),需要指定數(shù)據(jù)類(lèi)型。 Event.clipboardData.clearData([type]):清除剪貼板數(shù)據(jù),可以指定數(shù)據(jù)類(lèi)型。如果不指定類(lèi)型,將清除所有類(lèi)型的數(shù)據(jù)。 Event.clipboardData.items:一個(gè)類(lèi)似數(shù)組的對(duì)象,包含了所有剪貼項(xiàng),不過(guò)通常只有一個(gè)剪貼項(xiàng)。下面的示例是攔截用戶(hù)的復(fù)制操作,將指定內(nèi)容放入剪貼板。
const clipboardItems = [];document.addEventListener(’copy’, async (e) => { e.preventDefault(); try { let clipboardItems = []; for (const item of e.clipboardData.items) { if (!item.type.startsWith(’image/’)) {continue; } clipboardItems.push(new ClipboardItem({ [item.type]: item,}) ); await navigator.clipboard.write(clipboardItems); console.log(’Image copied.’); } } catch (err) { console.error(err.name, err.message); }});
上面示例中,先使用e.preventDefault()取消了剪貼板的默認(rèn)操作,然后由腳本接管復(fù)制操作。
cut事件則是在用戶(hù)進(jìn)行剪切操作時(shí)觸發(fā),它的處理跟copy事件完全一樣,也是從Event.clipboardData屬性拿到剪切的數(shù)據(jù)。
五、paste 事件用戶(hù)使用剪貼板數(shù)據(jù),進(jìn)行粘貼操作時(shí),會(huì)觸發(fā)paste事件。
下面的示例是攔截粘貼操作,由腳本將剪貼板里面的數(shù)據(jù)取出來(lái)。
document.addEventListener(’paste’, async (e) => { e.preventDefault(); const text = await navigator.clipboard.readText(); console.log(’Pasted text: ’, text);});
以上就是JS如何使用剪貼板操作Clipboard API的詳細(xì)內(nèi)容,更多關(guān)于JS如何使用剪貼板操作的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式2. AJAX實(shí)現(xiàn)文件上傳功能報(bào)錯(cuò)Current request is not a multipart request詳解3. ASP常用日期格式化函數(shù) FormatDate()4. vue-electron中修改表格內(nèi)容并修改樣式5. 微信小程序?qū)崿F(xiàn)商品分類(lèi)頁(yè)過(guò)程結(jié)束6. 推薦一個(gè)好看Table表格的css樣式代碼詳解7. 不使用XMLHttpRequest對(duì)象實(shí)現(xiàn)Ajax效果的方法小結(jié)8. 基于Surprise協(xié)同過(guò)濾實(shí)現(xiàn)短視頻推薦方法示例9. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總10. ASP新手必備的基礎(chǔ)知識(shí)
