复制,粘贴(navigator.clipboard.write(

2024-09-09  本文已影响0人  月下小酌_dbd5

复制

 let text = "123"
 navigator.clipboard.writeText(text).then(() => {
    ElMessage.success('复制成功')
  });
const shareRef = ref() //获取Dom元素
 // 新标准 注意此处是异步的
 try {
     const item = new window.ClipboardItem({
        "text/html": new Blob([shareRef.value.innerHTML], { type: "text/html" })
      });
      await navigator.clipboard.write([item]).then(function() {
        ElMessage.success('复制成功')
      }, function(err) {
        ElMessage.error('复制失败')
        console.error('err: ', err);
      })
    
   } catch (error) {
      ElMessage.error('复制失败')
   }

获取粘贴剪贴板的内容(监听addEventListener)

 if(inputRef.value) {
      inputRef.value.addEventListener('paste', async (event:any) => {
          // 在这里编写你想在粘贴时执行的代码
          // alert('内容已粘贴!');
          // 1.可以通过navigator.clipboard.readText()获取粘贴板的内容
          navigator.clipboard.readText().then(clipText => {
              console.log('粘贴的文本内容:', clipText);
          }).catch(error => {
              console.error('读取剪贴板失败:', error);
          });

          // 2.可以通过event.clipboardData.getData('text')获取粘贴板的内容
          var pastedData = event.clipboardData.getData('text');
          console.log(pastedData);
      });
    }
if(inputRef.value) {
      inputRef.value.addEventListener('paste', async (event:any) => {
        // 异步
        try {
          const clipboardItems = await navigator.clipboard.read();
          for (const clipboardItem of clipboardItems) {
            for (const type of clipboardItem.types) {
              const blob = await clipboardItem.getType(type);
              const html = await blob.text()
              // const tempHtml = html.replace(/<[^>]+>/g, '\n');
              const tempHtml1 = html.replace(/<\/d[^>]+>/g, '\n');
              const tempHtml2 = tempHtml1.replace(/<[^>]+>/g, '');

              console.log(html) //<div>123</div><div>456</>
              console.log(tempHtml2) // 123\n456
              // console.log(URL.createObjectURL(blob));
              inputValue.value = tempHtml2 // 赋值
            }
          }
        } catch (err:any) {
          console.error(err.name, err.message);
        }
      });
    }
上一篇 下一篇

猜你喜欢

热点阅读