js 获取剪切板内容

1. 粘贴事件

const items = (event.clipboardData || window.clipboardData).items
    const len = items.length
    let isFalg = true
    for (let i = 0; i < len; i++) {
        if (items[i].kind === 'file' && items[i].type.indexOf('image') !== -1) {
            isFalg = false
            // 图片格式
            const file = items[i].getAsFile() // 获取⽂件数据
            const blob = new Blob([file], { type: file.type })
            console.log('粘贴的是图⽚类型', blob, file)
            const formdate = new FormData()
            formdate.append('file', file)
        }
    }
    if (isFalg) {
        const html = (event.clipboardData || window.clipboardData).getData('text/html')
        if (html) {
            // html格式
        } else {
            // 字符串格式
            const text = (event.clipboardData || window.clipboardData).getData('text')
           
        }
    }

2. 手动获取

 navigator.permissions.query({ name: 'clipboard-read' }).then((result) => {
        if (result.state === 'granted' || result.state === 'prompt') {
            navigator.clipboard.read().then((data) => {
                for (let i = 0; i < data.length; i++) {
                    let contentType = data[i].types[data[i].types.length - 1]
                    data[i].getType(contentType).then((blob) => {
                        const reader = new FileReader()
                        if (contentType == 'text/html' || contentType == 'text/plain') {
                            // html 和 字符串
                            reader.readAsText(blob, 'utf-8')
 
                            reader.onload = function () {
                                 
                                console.log(reader.result);
                            }
                        } else {
                            // 图片
                            let file = new File([blob], uuid(), { type: contentType, lastModified: Date.now() });
                        }
                        

                    })

                }
            })
        }
    })

3. 写入剪切板

export const copySelect = (selArea) => {
    console.log("复制的内容:");
    console.log(selArea);
    const input = document.createElement('input')
    input.style.position = 'absolute'
    input.style.left = '-9999px'
    input.style.top = '-9999px'
    document.body.appendChild(input)
    input.value = selArea
    input.select()
    document.execCommand('copy')
    // console.log('复制成功')
    document.body.removeChild(input)
}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值