JavaScript 获取和设置剪贴板中的内容

  • JavaScript 获取和设置剪贴板中的内容已关闭评论
  • 155 次浏览
  • A+
所属分类:Web前端
摘要

通过 JavaScript 在浏览器中获取或设置剪贴板中的内容,常用于一键复制或使用网页油猴复制限制文本


通过 JavaScript 在浏览器中获取或设置剪贴板中的内容,常用于一键复制或使用网页油猴复制限制文本

使用 execCommand (已弃用)

写入文本到剪贴板

document.onclick = function() {   let text = 'hello world'   let dom_input = document.createElement('input')   dom_input.value = text   document.body.appendChild(dom_input)   dom_input.select()   document.execCommand("Copy")   dom_input.parentElement.removeChild(dom_input) } 

注意

用户和页面要先有交互(点击行为)才能复制成功

使用 clipboard (标准推荐)

提示

使用 clipboard 只能获取剪贴板中的文字和图片,并且需要用户授权,某些操作需要有用户交互(点击行为)

从剪贴板读取文本

navigator.clipboard.readText().then((text) => {   console.log(text) }, (error) => { console.log(error) }) 

从剪贴板读取文件

document.onclick = function() {   navigator.clipboard.read().then((file_list) => {     for(let item of file_list) {       for(let file_type of item.types) {         console.log('文件类型', file_type)         item.getType(file_type).then(res => {           if(['text/html', 'text/plain'].includes(file_type)) {             res.text().then(text => {               console.log(text)             }, (error) => { console.log(error) })           } else {             open(URL.createObjectURL(res))           }         }, (error) => { console.log(error) })       }     }   }, (error) => { console.log(error) }) } 

写入文本到剪贴板

navigator.clipboard.writeText('hello world').then(function() {   console.log('success') }, function(error) { console.log(error)} ) 

写入文件到剪贴板

let input = document.createElement('input') input.type = 'file' document.body.appendChild(input) input.onchange = function(ev) {   let f = ev.target.files[0]   let item = [ new ClipboardItem({ 'image/png': new Blob([f], {type: 'image/png'}) }) ] // 写入图片   let text = [ new ClipboardItem({ 'text/plain': new Blob(['hello world'], {type: 'text/plain'}) }) ] // 写入文本   navigator.clipboard.write(item).then(function() {     console.log('success')   }, function(error) { console.log(error) }) } 

注意

以上代码均在 Chrome 107.0.5304.88 测试通过,但不能保证其他浏览器也能用,其中 clipboard.write() 存在 bug 不建议使用。