首页 > 解决方案 > 无法将 html 格式的字符串复制到 Chrome 中的剪贴板

问题描述

我继续工作angular5,我必须从中复制一些HTML代码clipboard并将其粘贴到 Outlook 中。我已经为 IE 实现了这一点,但相同的代码在 chrome 中不起作用,chrome 根本不会复制任何东西,也不会显示任何控制台错误。

基本上,一旦我复制,我必须hyperlink在 Outlook 中创建一个并过去该超链接,当用户单击该链接时,应该打开一个带有该超链接 ref 的新页面。我的代码如下,请帮我实现chrome的复制功能?

public copyToClipboard {
  const body = document.createElement('body');
  const breakLine = document.createElement('br');
  const ol = document.createElement('ol');

  const range = document.createRange();
  document.body.appendChild(body);
  body.appendChild(ol);

  let name: string;
  this.selectedFiles.forEach(doc => {
    const docURL = this.serviceCall();
    const anchor = document.createElement('a');
    const li = document.createElement('li');

    anchor.href = docURL;
    anchor.text = doc.fileName;
    name = doc.name;
    body.appendChild(li).appendChild(anchor);
   });
    range.selectNode(body);

    window.getSelection().addRange(range);
    document.execCommand('copy');
    document.body.removeChild(body);
}

//HTML
<button pButton (click)="copyToClipboard()"></button>

(请忽略我的代码中是否有任何拼写错误,因为我输入了代码而不是复制+粘贴,此代码在 IE 中运行完美)

标签: htmltypescriptgoogle-chromeangular5clipboard

解决方案


我猜他们最近对异步 ClipboardAPI 的实现使 Chrome 改变了他们的行为 wrt execCommand('copy'),因为它现在看起来像是一个异步方法。
execCommand应该是一个同步方法,所以这被认为是一个浏览器错误。

现在解决方法是在删除源元素之前稍等片刻。

(另请注意,在这里使用 <body> 元素是一个坏主意,实际上是问题的另一部分)。

const obj = {
  serviceCall() { return Math.random();},
  selectedFiles: [
    { name: 'foo', fileName: 'foo.bar' },
    { name: 'bar', fileName: 'bar.foo' }
  ],
  copyToClipboard() {
    // don't use a <body> element
    const body = document.createElement('div');
    const breakLine = document.createElement('br');
    const ol = document.createElement('ol');

    const range = document.createRange();
    document.body.appendChild(body);
    body.appendChild(ol);

    let name = ""; // we're in pure js
    this.selectedFiles.forEach(doc => {
      const docURL = this.serviceCall();
      const anchor = document.createElement('a');
      const li = document.createElement('li');

      anchor.href = docURL;
      anchor.text = doc.fileName;
      name = doc.name;
      body.appendChild(li).appendChild(anchor);
    });
    range.selectNode(body);

    window.getSelection().addRange(range);
    document.execCommand('copy');
    // wait just a bit
    requestAnimationFrame(() =>
      document.body.removeChild(body)
    );
  }
}

btn.onclick = e => obj.copyToClipboard();
<button id='btn'>
  copy to clipboard
</button>
<textarea>paste here to check your clipboard's content</textarea>


推荐阅读