html - 无法将 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 中运行完美)
解决方案
我猜他们最近对异步 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>
推荐阅读
- android - Recyclerview 移至屏幕外可见性
- python - Boto3 Python Lambda自定义返回错误
- java - 如何从 XML 中获取哈希以登录 java
- java - Java 套接字服务器,在集群服务器上
- vb.net - 如何创建仅适用于支持特定接口的类的泛型类?
- python - 如何在 Google Colab 上安装 nvidia apex
- angular - Angular 2+ Universal 页面未在服务器上呈现
- python - 读取 CSV 并调用第三方 API 性能问题
- c# - 无法使用 [] 将索引应用于“System.Collections.Generic.HashSet”类型的表达式
' - python - 未加权图中的路径:从源头到源头的最短行程,施加一个点