通過 JavaScript 在瀏覽器中獲取或設定剪貼板中的內容,常用于一鍵復制或使用網頁油猴復制限制文本
使用 execCommand (已棄用)
寫入文本到剪貼板
document.onclick = function() {
let text = 'hello world'
let dom_input = document.createElement('input')
dom_input.value = https://www.cnblogs.com/adore/archive/2022/10/29/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 不建議使用,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523132.html
標籤:其他
上一篇:虎牙直播插件
下一篇:1.1 仿百度Web Day1
