修改剪切板数据

在后台管理系统的展示JSON数据的时候用到了React-JSON-View这个组件,同事在使用其复制功能时反馈到每次复制字符串都会带上",这很讨厌让我处理下。此为背景。

原以为组件会提供配置项来控制复制的值,但事实并没有……
我看了下他的源码,他自己在CopyToClipboard.js中实现的(clipboard.js也是这种实现):

1
2
3
4
5
6
7
8
9
10
11
12
13
const container = document.createElement('textarea');

container.innerHTML = JSON.stringify(
this.clipboardValue(src),
null,
' '
);

document.body.appendChild(container);
container.select();
document.execCommand('copy');

document.body.removeChild(container);

他通过JSON.stringify转换的值(所以字符串多了”),既然他们没有提供配置项,那我就只能监听copy事件了:

1
2
3
4
5
6
document.addEventListener('copy', event => {
const text = event.srcElement.innerHTML.replace(/"/g, '');
event.clipboardData.setData('text/plain', text);
// 一定要阻止浏览器默认行为
event.preventDefault();
});

这里解释一下event.srcElement.innerHTML:

因为copy命令产生的ClipboardEvent事件,clipboardData数据为空:

1
2
3
4
5
6
7
clipboardData: DataTransfer
dropEffect: "none"
effectAllowed: "uninitialized"
files: FileList {length: 0}
items: DataTransferItemList {length: 0}
types: []
__proto__: DataTransfer

当我们调用了event.clipboardData.setData('text/plain', text), 再看数据:

1
2
3
4
5
6
7
8
9
dropEffect: "none"
effectAllowed: "uninitialized"
files: FileList {length: 0}
items: DataTransferItemList {0: DataTransferItem, length: 1}
types: Array(1)
0: "text/plain"
length: 1
__proto__: Array(0)
__proto__: DataTransfer

这时剪切板中的数据就是我们修改后的数据了。

目前有新的方法navigator.clipboard来对剪切板进行操作,不过现阶段兼容性和限制较多,暂时了解下就好了。目前这块使用频率较低,就暂时未做更深的了解。

参考

Interact_with_the_clipboard

execCommand

0%