read()
方法在
Clipboard
interface requests a copy of the clipboard's contents, delivering the data to the returned
Promise
when the promise is resolved. Unlike
readText()
,
read()
method can return arbitrary data, such as images. This method can also return text.
To read from the clipboard, you must first have the
"clipboard-read"
permission.
注意: The asynchronous Clipboard and Permissions APIs are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like. Be sure to review the 兼容性表格 before using these methods.
var promise = navigator.clipboard.read();
None.
A
Promise
that resolves with a
DataTransfer
object containing the clipboard's contents. The promise is rejected if permission to access the clipboard is not granted.
After using
navigator.permissions.query()
to find out if we have (or if the user will be prompted to allow)
"clipboard-read"
access, this example fetches the data currently on the clipboard. If it's not a png image, an error message is presented. Otherwise, an image element referred to using the variable
imgElem
has its source replaced with the clipboard's contents.
// First, ask the Permissions API if we have some kind of access to
// the "clipboard-read" feature.
navigator.permissions.query({name: "clipboard-read"}).then(result => {
// If permission to read the clipboard is granted or if the user will
// be prompted to allow it, we proceed.
if (result.state == "granted" || result.state == "prompt") {
navigator.clipboard.read().then(data => {
for (let i=0; i<data.items.length; i++) {
if (data.items[i].type != "image/png") {
alert("Clipboard contains non-image data. Unable to access it.");
} else {
const blob = data.items[i].getType("image/png");
imgElem.src = URL.createObjectURL(blob);
}
}
});
}
});
注意:
At this time, while Firefox does implement
read()
, it does not recognize the
"clipboard-read"
permission, so attempting to use the
权限 API
to manage access to the API will not work.
| 规范 | 状态 | 注释 |
|---|---|---|
|
Clipboard API and events
The definition of 'read()' in that specification. |
工作草案 | 初始定义。 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
read
|
Chrome
部分支持
76
|
Edge 79 |
Firefox
63
Disabled
|
IE No | Opera 63 | Safari 13.1 |
WebView Android
部分支持
84
|
Chrome Android
部分支持
84
|
Firefox Android
63
Disabled
|
Opera Android 54 | Safari iOS 13.4 | Samsung Internet Android 12.0 |
完整支持
部分支持
不支持
见实现注意事项。
用户必须明确启用此特征。
Clipboard
read()
readText()
write()
writeText()