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

相关推荐
Rysxt_7 分钟前
Vuex 教程 从入门到实践
前端·javascript·vue.js
xuehuayu.cn1 小时前
js es6 class 类中的值是异步赋值, 子类中如何获取这个值?
javascript·es6
威风的虫1 小时前
ES6 数组方法:告别循环,拥抱函数式编程
开发语言·前端·javascript
小杨快跑~1 小时前
ES6 Promise:告别回调地狱的异步编程革命
前端·javascript·ecmascript·es6
r0ad2 小时前
读诗的时候我却使用了自己研发的Chrome元素截图插件
前端·javascript·chrome
知识分享小能手3 小时前
jQuery 入门学习教程,从入门到精通, jQuery在HTML5中的应用(16)
前端·javascript·学习·ui·jquery·html5·1024程序员节
七号练习生.c3 小时前
JavaScript基础入门
开发语言·javascript·ecmascript
baozj3 小时前
🚀 手动改 500 个文件?不存在的!我用 AST 撸了个 Vue 国际化神器
前端·javascript·vue.js
molly cheung4 小时前
FetchAPI 请求流式数据 基本用法
javascript·fetch·请求取消·流式·流式数据·流式请求取消
Mintopia5 小时前
🧠 量子计算对AIGC的潜在影响:Web技术的未来可能性
前端·javascript·aigc