做个有深度的程序员 — YuanGe
浏览器粘贴板操作
浏览器粘贴板操作

浏览器粘贴板操作

使用场景

比如:分享一个商品或者文章,点击按钮直接将口令获取地址写进粘贴版,生成海报直接写进粘贴板、粘贴图片上传等等

写入粘贴版

     <button onclick="copy1()">复制文本 </button>
    <button onclick="copy2()">复制html</button>
    <button onclick="copy3()">复制图片</button>

       function copy1() {
            navigator.clipboard.writeText('复制文本')
        }
        function copy2() {
            const data = new Blob(['<b style="color:red">复制html</b>'], { type: 'text/html' })
            const item = new ClipboardItem({ 'text/html': data })
            navigator.clipboard.write([item])
        }
        async function copy3() {
            const res = await fetch('./img.png')
            const data = await res.blob()

            const item = new ClipboardItem({'image/png':data})
            navigator.clipboard.write([item])
        }

写入图片这里不支持 ‘image/jpg’

读取粘贴板

<button onclick="read1()">读取剪切版文本</button>
    <button onclick="read2()">读取剪切版图片</button>
    <div class="editor" contenteditable="true"></div>

<script>
        async function read1() {
            const text = await navigator.clipboard.readText()
            editor.innerHTML = text
        }
        async function read2() {
            const data = await navigator.clipboard.read()
            console.log(data);
            editor.innerHTML = ''
            const item = data[0]
            item.types.forEach(async k => {
                const blod = await item.getType(k);
                if (k == 'text/html') {
                    editor.innerHTML = await blod.text()
                } else {
                    const img = document.createElement('img')
                    img.src = URL.createObjectURL(blod)
                    editor.appendChild(img)
                }
            })
        }
      
    </script>
-->