简体   繁体   English

将本机 HTML 粘贴到浏览器剪贴板

[英]Pasting native HTML to browser clipboard

With a button click, a user will have HTML content from the current page into the clipboard.通过单击按钮,用户会将当前页面中的 HTML 条内容放入剪贴板。 Then, in an email, paste the content with the HTML formatting preserved.然后,在 email 中,粘贴保留 HTML 格式的内容。 The desire is to replicate the selecting of content in the browser window, without making the user do the selecting (separate view).希望在浏览器 window 中复制内容的选择,而不让用户进行选择(单独的视图)。

I have most of this setup and working.我有大部分的设置和工作。 I don't believe there are permissions issues.我不认为存在权限问题。 However, with the below code, I get "pasted", yet then pasting (CTRL+V) following that, there is nothing in the paste buffer.但是,使用下面的代码,我得到了“粘贴”,但随后粘贴 (CTRL+V),粘贴缓冲区中没有任何内容。 If I switch it to clipboard.writeText() , I get the html as plaintext.如果我将它切换到clipboard.writeText() ,我会得到 html 作为明文。 It's just using the Blob for html that causes the paste buffer to be empty.它只是使用 html 的Blob导致粘贴缓冲区为空。

I think it relates to the Blob part, maybe the text/html part is wrong?我认为它与Blob部分有关,也许text/html部分是错误的? Is there a way to get this to work?有没有办法让它工作?

<div id="lipsum" contenteditable="true" style="display: none;">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  <p>Vivamus mollis, augue eu vulputate fermentum.</p>
</div>
<script>
(function() {
  let html = document.getElementById('lipsum').innerHTML
  let content = new Blob([ html ], { type: 'text/html' })
  let data = [ new ClipboardItem({ [ content.type ]: content }) ]
  
  window.focus()

  setTimeout(() => {
    navigator.clipboard.write(data).then(
      () => console.log('pasted'),                   <<< This fires
      (error) => console.log('not pasted', error)
    )
  }, 2000)
})()
</script>

Your code worked for me on Chrome.你的代码在 Chrome 上对我有用。 I was able to paste the div contents after loading the page and waiting a couple seconds.加载页面并等待几秒钟后,我能够粘贴 div 内容。 I did notice errors if I didn't continuously have the page focused.如果我没有持续关注页面,我确实注意到了错误。 Eg when I would keep the inspector window forward it would error.例如,当我让检查员 window 保持转发时,它会出错。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Test</title>
</head>
<body>
<div id="lipsum" contenteditable="true" style="display: none;">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  <p>Vivamus mollis, augue eu vulputate fermentum.</p>
</div>

<script>
  (function() {
    let html = document.getElementById('lipsum').innerHTML
    let content = new Blob([ html ], { type: 'text/plain' })
    let data = [ new ClipboardItem({ [ content.type ]: content }) ]

    setTimeout(() => {
      window.focus()
      navigator.clipboard.write(data).then(
        () => console.log('pasted'),
        (error) => console.log('not pasted', error)
      )
    }, 2000)
  })()</script>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM