复制粘贴(二):操作剪贴板 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 中,结果:

相关推荐
YukiMori2317 小时前
一个有趣的原型继承实验:为什么“男人也会生孩子”?从对象赋值到构造函数继承的完整推演
前端·javascript
摸鱼的春哥18 小时前
惊!黑客靠AI把墨西哥政府打穿了,海量数据被黑
前端·javascript·后端
小兵张健18 小时前
Playwright MCP 截图标注方案调研(推荐方案1)
前端·javascript·github
我叫黑大帅21 小时前
Vue3和Uniapp的爱恨情仇:小白也能懂的跨端秘籍
前端·javascript·vue.js
None32121 小时前
【NestJs】使用Winston+ELK分布式链路追踪日志采集
javascript·node.js
Qinana21 小时前
从代码到智能体:MCP 协议如何重塑 AI Agent 的边界
前端·javascript·mcp
Marshall1511 天前
zzy-scroll-timer:一个跨框架的滚动定时器插件
前端·javascript
明月_清风1 天前
打字机效果优化:用 requestAnimationFrame 缓冲高频文字更新
前端·javascript
明月_清风1 天前
Markdown 预解析:别等全文完了再渲染,如何流式增量渲染代码块和公式?
前端·javascript
程序猿的程2 天前
开源一个 React 股票 K 线图组件,传个股票代码就能画图
前端·javascript