clipboard 剪贴板

325 阅读2分钟

前言

平时我们也会时不时用到剪贴板的功能,使用上很简单,尤其是文本操作的,但是有时候也会阻止复制、粘贴文件的操作,并且还在一些环境下存在无法使用的问题,这里面就简单介绍一下

clipboard 剪贴板

直接写入到 clipboard

一般是调用按钮写入固定内容

//写入粘贴板
navigator.clipboard.writeText("我是联盟第一辅助")

//实际上 button 也有一个 data-clipboard-target 属性
//只需要传入指定节点的 id选择器名称,就可以复制
<button data-clipboard-target="#demoInput">点我复制</button>

读取 clipboard 文本

//读取粘贴板文本,可能会失败,那就是没授权
navigator.clipboard.readText().then((text) => {
    console.log(text);
});

监听复制 copy

我们可以直接监听 copy 事件,并阻止,也可以更新粘贴内容

document.addEventListener("copy", (e) => {
    //阻止用户在当前页面复制
    e.preventDefault();
    //当然除了阻止也可以更新剪贴板内容
    navigator.clipboard.writeText("版权归我虽有,违法必究")
});

粘贴 paste

有时我们会监听粘贴时间,遇到剪裁粘贴过来的文件,我们可以直接就拿到文件信息上传,返回 url 到编辑器了,编辑器显示本地或者 url 的图片内容,也可以直接粘贴文本,混砸的这边就不多说了

粘贴普通文本

这类直接粘贴文本到指定 dom

document.addEventListener("paste", (e) => {
    //e.clipboard.files 这就是粘贴板上的文件信息,文件可以直接上传也可以显示
    const dom = document.querySelector("#paste-div");
    if (!dom) return 
    navigator.clipboard.readText().then((text) => {
        dom.innerHTML = text;
    });
});

复制文件,读取文件

我们可以直接获取文件内容,然后创建图片节点显示到页面上,也可以直接上传,都是没问题的

document.addEventListener("paste", (e) => {
    const files = e.clipboardData?.files;
    if (!files || files.length < 1) return;
    //我们假设只取第一张图片
    //读取后,我们直接创建一张图片到页面上吧
    const reader = new FileReader();
    reader.onload = (e) => {
        const img = document.createElement("img");
        img.src =  e.target.result; //result就是我们的图片内容
        const root = document.querySelector("#root");
        root.appendChild(img);
    };
    reader.readAsDataURL(files[0]);
});

clipboard 兼容性与 execCommand

clipboard 好用是好用,但是兼容性不好,如果没有授权、一些低版本浏览器、http浏览器环境下,其返回的是 undefined,那么我们在此环境下就要使用 execCommand 了, execCommand 需要配合 input、textarea使用,相对比较麻烦,且即将丢弃,但作为兼容性代码还是可以使用的

ps:吐槽一下,低版本和没权限也就忍了,http 也不行这就说不过去了,就算是 https 在浏览器环境安全仍然堪忧,多此一举呀,还不如直接一口气封装好一个兼容性方法😂

document.execCommand("copy") //复制;
document.execCommand("paste") //粘贴
document.execCommand("cut") //剪切

下面就以一个 copy 为例,写一个兼容性代码

function copyText(text: string) {
    //有 clipboard 我们就是用,没有就不适用
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text);
    } else {
        const input = document.createElement("input");
        input.setAttribute("value", text);
        document.body.appendChild(input);
        input.select();
        document.execCommand("copy");
        document.body.removeChild(input);
    }
}