浏览器剪切板兼容性

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Paste</title>
</head>
<body>
  <textarea name="" id="" cols="30" rows="10"></textarea>
   <script>
     
     async function richPaste(clipboard, content) {
      console.log(clipboard)
      const items = await clipboard.read()
      console.log(items)
      if(Object.prototype.toString.call(items) !== "[object Array]"){
        for (const item of items.items) {
            if(item.type !== "text/rtf") {
                item.getAsString( str => {
                    document.write(str)
                })
            }
        }
      } else {
        for (const item of items) {
            for (const type of item.types) {
                item.getType(type).then( res => {
                    console.log(res)
                    res.text().then( str => {
                        console.log(str)
                        document.write(str)
                    })
                }).catch( err => {
                    console.log(err)
                })
            }
        }
      }
      
     }

      window.onload = function(){
        var clipboard = window.navigator.clipboard
        var content = document.getElementById("content")
        console.log(content)
        document.addEventListener("paste", function(e){
          console.log(e)
          richPaste(clipboard, content)
        })
      }
   </script>

   <div id="content"></div>
</body>
</html>

  

posted @ 2023-08-20 17:17  winyh  阅读(29)  评论(0编辑  收藏  举报