JsonTree的剪贴板API



我正在尝试将JSON设置复制到剪贴板

const settings = {
"id": "1",
"properties": {
"conjunction": "AND",
"not": false
},
"children": {
"1": {
"type": "userSettings",
"properties": {
"field": "name",
"operator": "equal",
"value": [
"Foo"
],
"valueSrc": [
"value"
],
"valueType": [
"text"
]
}
}
}
});

navigator.clipboard.write(settings)导致以下错误:

Argument of type 'JsonTree' is not assignable to parameter of type 'ClipboardItems'.
Type 'JsonGroup' is missing the following properties from type 'ClipboardItem[]': length, pop, push, concat, and 29 more.

但我真的需要它是JsonTree,因为上面的设置是硬编码的,但实际上我想从一个视图复制我的设置,并按原样粘贴到另一个视图中,也就是说以JsonTree的格式。有办法吗?

我的代码的第一个问题是clipboard.write((需要ClipboardItem,而Firefox不支持它。

然而,只是为了看看是否可以达到预期的结果,我尝试了一下。第一步是创建一个字符串,如这里所写的clipboardapi/#写入剪贴板只支持三种类型:text/plain、text/html、image/png。因此,我现在无法将json写入剪贴板。所以代码是下面的

const string = JSON.stringify(filterTree)
navigator.clipboard.write([
new ClipboardItem({
'text/plain': new Blob([string], {
type: 'text/plain',
}),
}),
); 

然而,更好的方法是使用navigator.clipboard.writeText(JSON.stringify(settings)),因为它也这样做,但需要更少的代码,并且所有浏览器都支持它。

最新更新