复制粘贴之 navigator.clipboard和document.execcommand

目前来说复制粘贴可以使用以下两种方法

if (window?.isSecureContext) {
   const blob = new Blob([tableHtml], { type: 'text/html' })
   /* global ClipboardItem*/
   navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })])
 }


document.execCommand('copy')

document.execCommand不定期会废弃,但是目前不影响使用,不看不知道,一看吓一跳,才知道document.execCommand有这么多功能


image.png

下面来具体看看有哪些功能:

语法

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

返回值

一个 Boolean ,如果是 false 则表示操作不被支持或未被启用。

注意:在调用一个命令前,不要尝试使用返回值去校验浏览器的兼容性

命令

  • copy 复制选中内容到剪贴板上
  • createLink 为选中的内容添加上超链接
  • paste 在光标位置粘贴剪贴板的内容,如果有被选中的内容,会被替换
  • removeFormat 对所选内容去除所有格式

更多参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand

你可能感兴趣的:(复制粘贴之 navigator.clipboard和document.execcommand)