程序員的眾多稱號里的一個叫“CV戰神”,但又有多少人知道cv的更多東西呢?
一起來看下cv下還隱含多少東西:
1.復制一段文字到剪切板
2.直接往剪切板寫一段內容
3.從剪切板獲取內容
復制文本到剪切板:
1 // 復制內容到剪切板 2 copyFn(value){ 3 let transfer = document.createElement('input'); 4 document.body.appendChild(transfer); 5 transfer.value = value; // 這里表示想要復制的內容 6 transfer.focus(); 7 transfer.select(); 8 if (document.execCommand('copy')) { 9 document.execCommand('copy'); 10 } 11 transfer.blur(); 12 // message.success('復制成功'); 13 document.body.removeChild(transfer); 14 }
通過這個方法會把value復制到剪切板的'text/plain'區域,你要是注冊了copy的監聽,會觸發你的監聽。
直接將要復制的內容放到剪切板
1 // 復制內容到剪切板 2 clipboardWrite(value){ 3 window.navigator.clipboard.writeText(value) 4 .then(() => { 5 console.log('Text copied to clipboard'); 6 }) 7 .catch(err => { 8 // This can happen if the user denies clipboard permissions: 9 console.error('Could not copy text: ', err); 10 }); 11 }
通過這個方法會把value復制到剪切板的'text/plain'區域,你要是注冊了copy的監聽,不會觸發你的監聽。
從剪切板獲取內容
1 // 獲取剪切板的數據 2 async pasteHandler(){ 3 const clipboardItems = await window.navigator.clipboard.read(); 4 let textHtml,textPlain; 5 for (const clipboardItem of clipboardItems) { 6 for (const type of clipboardItem.types) { 7 const item = await clipboardItem.getType(type); 8 if(item && item.type == 'text/html'){ 9 textHtml = await item.text(); 10 } 11 if(item && item.type == 'text/plain'){ 12 textPlain = await item.text(); 13 } 14 } 15 } 16 return {textHtml,textPlain} 17 }
方法中item會有四種類型,文本和html還有圖片還有什么 ,忘卻了,有需要的自己打印看看。
當然navigator.clipboard.readText()直接可以讀取‘text/plain’的值,但如果你復制的是Excel的數據的話,通過這個方法獲取到的只是一些文本和箭頭。
研究了半天怎么用js觸發ctrl+c和ctrl+v的事件,但也沒有效果,哪位大佬成功了望不吝賜教。
over!
以上方法在谷歌是沒問題的,但在火狐上就不行了,火狐的安全策略不允許你區讀取粘貼板的內容,也就是說window.navigator.clipboard.read是不存在的 ,調用這個方法是會報錯的,
總不能谷歌點擊正常操作,火狐點擊就報錯吧,
費勁半天找到一個很low(但能想到的最好的方法就是這個了)的解決方式:
就是alert一段文字:請你使用ctrl+v進行粘貼。。。。
完美解決!
但如果用戶不滿意,就想點擊粘貼,咋辦?那就去開啟權限去,開啟權限后就能完美實現了。
開啟權限方法:火狐瀏覽器地址欄輸入:about:config,回車,然后點同意,然后搜索以下倆個權限,開啟,然后回來刷新界面就能實現粘貼了:
當然寫法和谷歌的默認寫法也是不一樣的:
const clipboardItems = await window.navigator.clipboard.read(); let items = clipboardItems.items; for (let i = 0; i < items.length; i++) { const item = items[i]; if(item && item.type === 'text/html'){ item.getAsString(text_html=>{ console.log("text_html >>: ", text_html); }); } if(item && item.type === 'text/plain'){ item.getAsString(text_plain=>{ console.log("text_plain >>: ", text_plain); }); } }
over