复制粘贴(二):操作剪贴板 navigator.clipboard

使用 navigator.clipboard 可以随时获取剪贴板对象(也就是说,在 copy/paste 事件外也可以用)

但是,此操作必须用户允许:

readText

readText() 获取剪贴板中的文本内容

html 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <div>
      <p>文字<input type="button" value="按钮" /><span>hello</span></p>
    </div>
    <input type="button" value="查看剪切板文本" onclick="getClipboardText()" />
    <script>
      async function getClipboardText() {
        const text = await navigator.clipboard.readText();
        console.log(text);
      }
    </script>
  </body>
</html>

选择 div 中的全部内容,复制

点击"查看剪切板文本按钮",控制台输出:文字hello

read

read() 获取剪贴板内容

js 复制代码
async function getClipboard() {
  const clipboardItems = await navigator.clipboard.read();
  for (const clipboardItem of clipboardItems) {
    const types = clipboardItem.types;
    // console.log("types", types); // 输出 ['text/plain', 'text/html']
    for (const type of types) {
      const blob = await clipboardItem.getType(type);
      const blobText = await blob.text();
      console.log(type, blob, blobText);
    }
  }
}

输出结果:

上图的含义是:剪贴板中有两类数据:text/plain(纯文本) 、 text/html(文本格式存储的html)

纯文本数据内容是:文字hello

html 数据内容是:<span>文字</span><input type="button" value="按钮"/><span>hello</span>(省略style属性)

writeText

js 复制代码
async function setClipboard() {
  await navigator.clipboard.writeText("你好");
}
write
html 复制代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <!-- 粘贴到可编辑的div中,能直观的看到效果 -->
    <div contenteditable="true" style="height: 80px; background: #eee"></div>
    
    <input type="button" value="设置剪贴板" onclick="setClipboard()" />
    <script>
      async function setClipboard() {
        await navigator.clipboard.write([
          new ClipboardItem({
            "text/html": new Blob([`<span style="background:red">haha</span>`], {
              type: "text/html",
            }),
          }),
        ]);
      }
    </script>
  </body>
  </body>
</html>

为了方便演示效果,准备一个 contenteditable= true 的 div:

点击"设置剪贴板"按钮,然后粘贴到 div 中,结果:

相关推荐
2501_946244788 分钟前
Flutter & OpenHarmony OA系统下拉刷新组件开发指南
开发语言·javascript·flutter
_Kayo_11 分钟前
React useState setState之后获取到的数据一直是初始值
前端·javascript·react.js
yang9yun19 分钟前
PostMan加载三方JS
javascript·测试工具·postman
Object~24 分钟前
2.变量声明
开发语言·前端·javascript
释怀不想释怀31 分钟前
vue前端crud(页面布局,新增,vue中反向代理)
前端·javascript·vue.js
zpjing~.~40 分钟前
iframe和父页面消息通信
开发语言·前端·javascript
释怀不想释怀3 小时前
Ajax,vue生命周期(自动加载页面发出请求)Axios
前端·javascript·ajax
cz追天之路9 小时前
华为机考--- 字符串最后一个单词的长度
javascript·css·华为·less
五颜六色的黑10 小时前
vue3+elementPlus实现循环列表内容超出时展开收起功能
前端·javascript·vue.js
EnoYao11 小时前
Markdown 编辑器技术调研
前端·javascript·人工智能