Clipboard.write()

您正在阅读此内容的英文版本,因为该语系尚未翻译。 帮助我们翻译此文章吧!

 

 

 

Clipboard 的方法 write() 写入图片等任意的数据到剪贴板。 这个方法可以用于实现剪切和复制的功能。

但是你要提前获取 "Permissions API" 的 "clipboard-write" 权限才能将数据写入到剪贴板。

注意: 浏览器对这个异步剪贴板的 API 仍然在讨论中。所以在使用它之前请检查 compatibility table 和 Clipboard availability in Clipboard 以获得更多的兼容性信息。

语法

var promise = navigator.clipboard.write(dataTransfer)

参数

dataTransfer
DataTransfer 对象包含了要写入剪贴板的数据。

返回值

当数据被写入到剪贴板的时候,Promise resolve 回调被执行。如果剪贴板不能完成剪贴操作,Promise  reject 回调被执行。

示例

这个例子展示了如何将当前剪贴板的内容替换为给定的内容。

function setClipboard(text) {
  let data = new DataTransfer();

  data.items.add("text/plain", text);
  navigator.clipboard.write(data).then(function() {
    /* success */
  }, function() {
    /* failure */
  });
}

代码创建了一个 DataTransfer 对象,要替换的内容存储在这里。执行 DataTransferItemList.add() 将数据写入进去,然后执行 write() 方法,指定执行成功或错误的结果。

规范

规范 状态 备注
Clipboard API and events
write()
Working Draft Initial definition.

浏览器兼容性

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
writeChrome Full support 76Edge No support NoFirefox Full support 63
Notes Disabled
Full support 63
Notes Disabled
Notes Currently works exactly like writeText(), including the availability limitations currently imposed by Firefox.
Disabled From version 63: this feature is behind the dom.events.asyncClipboard.dataTransfer preference (needs to be set to true). To change preferences in Firefox, visit about:config.
IE No support NoOpera Full support 63Safari No support NoWebView Android Full support 76Chrome Android Full support 76Firefox Android Full support 63
Notes Disabled
Full support 63
Notes Disabled
Notes Currently works exactly like writeText(), including the availability limitations currently imposed by Firefox.
Disabled From version 63: this feature is behind the dom.events.asyncClipboard.dataTransfer preference (needs to be set to true). To change preferences in Firefox, visit about:config.
Opera Android No support NoSafari iOS No support NoSamsung Internet Android ?

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.