JS原生 復(fù)制粘貼

本篇文章不考慮瀏覽器兼容,谷歌瀏覽器親測(cè)至少得88版本往上。Mac系統(tǒng)復(fù)制粘貼html數(shù)據(jù),會(huì)自動(dòng)加一些標(biāo)簽,小伙伴們自己測(cè)吧。一般需求用不著。

想要實(shí)現(xiàn)復(fù)制粘貼就只需要搞明白兩件事就可以了。

第一就是如何往粘貼板里邊存放數(shù)據(jù),第二就是如何讀取粘貼板里邊的數(shù)據(jù)。

所操作的數(shù)據(jù)大致可以分為三類數(shù)據(jù) 1:字符串 2:帶樣式的HTML 3:圖片 還有其他數(shù)據(jù)格式,還請(qǐng)各位小伙伴補(bǔ)充指教吧。

第一 如何往粘貼板里邊放數(shù)據(jù)

① 如果只是放普通字符串是最簡(jiǎn)單的

navigator.clipboard.writeText('通過簡(jiǎn)單方法,往剪切板寫入這句話');

② 想要放入帶格式的數(shù)據(jù),比如想要往word內(nèi)粘貼一個(gè)表格,跟正常寫html標(biāo)簽加寫樣式是一樣的

<button onclick="putHTML2Clipboard()">往粘貼板內(nèi)放帶樣式/格式的數(shù)據(jù)</button>
async function putHTML2Clipboard() {
    const html = `
        <table width="568" style="border-collapse:collapse;">
            <tr>
                <td width="81" style="border: 1.0pt solid red">
                <p>中文</p>
                </td>
                <td width="16" style="border:solid windowtext 1.0pt;">
                <p>另外的單元格</p>
                </td>
            </tr>
        </table>`
    const htmlBlobABC = new Blob([html], { type: "text/html" })
    const item = new ClipboardItem({
        [htmlBlobABC.type]: htmlBlobABC
    })
    await navigator.clipboard.write([item]);
    console.log("HTML數(shù)據(jù)復(fù)制成功,快去word內(nèi)粘貼試試吧");
}

③往粘貼板內(nèi)放入圖片,目前只支持放png圖片

<button onclick="putNetWorkPic2Clipboard()">往粘貼板內(nèi)放網(wǎng)絡(luò)圖片</button>
async function putNetWorkPic2Clipboard() {
    const imgURL = 'xxx'; // 自己去網(wǎng)上隨便找個(gè)png的圖片,把地址貼這兒就可以
    const data = await fetch(imgURL);
    const anyName = await data.blob();
    await navigator.clipboard.write([
        new ClipboardItem({
            [anyName.type]: anyName,  // 注意這個(gè)anyName 任意名字(隨便寫) 但是要對(duì)應(yīng)上 
        }),
    ]);
    console.log('網(wǎng)絡(luò)圖片復(fù)制成功,快去word內(nèi)粘貼試試吧');
}
<button onclick="putLocalPic2Clipboard()">往粘貼板內(nèi)放本地圖片</button>
async function putLocalPic2Clipboard() {
        const data = await fetch("./pic/testPng.png");
            const anyName = await data.blob();
            // const str = new Blob(["測(cè)試用的字符串"], { type: "text/plain" });
            await navigator.clipboard.write([
                new ClipboardItem({
                    [anyName.type]: anyName,  // 注意這個(gè)anyName 任意名字(隨便寫) 但是要對(duì)應(yīng)上 
                    // [str.type]: str,  // 目前也不支持多個(gè)
                }),
            ]);
}

其實(shí)也可以用放HTML的方式,把圖片放入粘貼板內(nèi)

第二:讀取粘貼板內(nèi)的數(shù)據(jù)

<!-- 模擬在這個(gè)div區(qū)域內(nèi)按Ctrl + V 粘貼 contenteditable="true" 是允許該div可編輯的意思 可以看到粘貼的結(jié)果 -->
<div class="target" contenteditable="true"></div>
const target = document.querySelector("div.target");
target.addEventListener('paste', pasteFun);
// 讀取剪切板示例
async function pasteFun(e) {

    // e.preventDefault(); 這里邊的return 并不能阻止粘貼 只是阻止下邊的程序執(zhí)行 如果要阻止粘貼行為 就用 阻止默認(rèn)行為事件 可以自己拿到粘貼板內(nèi)的數(shù)據(jù) 自己控制粘貼行為
    const items = await navigator.clipboard.read();
    const item = items[0];
    
    // 如果粘貼板內(nèi)有HTML類型的數(shù)據(jù)和純文本的數(shù)據(jù),可以選擇要哪種的
    if (item.types.length === 1 && item.types[0] === "image/png") { // 并不能拿到復(fù)制的文件夾內(nèi)的圖片
        const imgBlob = await item.getType("image/png"); // 這是拿到了圖片的blob數(shù)據(jù)
        // 然后將圖片的blob數(shù)據(jù)轉(zhuǎn)為base64 就可以使用了
        let reader = new FileReader()
        reader.readAsDataURL(imgBlob)
        reader.onload = (e) => {
            // e.target.result 就是圖片的base64
            const base64 = e.target.result;
            const img = document.createElement("img");
            img.src = base64;
            document.body.appendChild(img);
        }
        return
    }
    if (item.types.includes("text/html")) { 
        const htmlBlob = await item.getType("text/html");
        const html = await new Response(htmlBlob).text();
        console.log(html, "html");
        return
    }
    
    // 如果只要純文本
    const plainBlob = await item.getType("text/plain");
    const plain = await new Response(plainBlob).text();
    console.log(plain, "純文本");
    
    const resStr = e.clipboardData.getData('text'); // 如果確定只要普通字符串 這個(gè)更簡(jiǎn)單些
    console.log("這應(yīng)該是獲取的文本", resStr)
    
}

轉(zhuǎn)載還請(qǐng)注明出處

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容