關于js復制內容到瀏覽器剪貼板報錯:Cannot read properties of undefined (reading ‘writeText‘)的解決方案
如果想直接看解決方案,請下滑到最后【完整代碼】處
問題描述
開發(fā)「復制」功能
根據使用瀏覽器提供的原生功能 navigator.clipboard
返回的 Clipboard
對象的方法 writeText()
寫文本到剪貼板。
在本地開發(fā),或者說是在使用http://127.0.0.1:8088
或者 http://localhost:8088
本地調試時,是沒有問題的,但是如果使用綁定 host 或者使用不安全域(域名+http)時,使用此功能,就會發(fā)生下面的報錯:
Uncaught TypeError: Cannot read properties of undefined (reading 'writeText')
原因分析
安全問題
想必各位小伙伴或多或少會做過這樣的操作,復制一下自己的個人信息然后粘貼到其他地方,看是所謂的方便如果遇到惡意有毒的釣魚網站,那存在剪切板的信息就會一覽無余,網絡信息安全一直都是重中之重,所以在這方面上 navigator.clipboard
算是做足了防備。
SO~ 原因就是 瀏覽器禁用了非安全域的 navigator.clipboard
對象。
安全域包括本地訪問與開啟TLS安全認證的地址,如 https 協(xié)議的地址、127.0.0.1 或 localhost 。
問題解決
所以要解決這個問題就是要做一個兼容的寫法,當我們處于在安全域下使用 navigator.clipboard
提升效率,非安全域時退回到 document.execCommand('copy')
保證我們的復制功能一直可用。
document.execCommand
這里先說一下 document.execCommand
寫過原生 Editor 編輯器大家應該都知道這個API吧,API 里面有很多方法,如:加粗/斜體/字號/字體顏色/插入圖片/插入鏈接/復制/剪切/撤銷… 具體可以看 MDN【但是這個API已經被官方廢棄掉了】
「復制」功能示例:
function copy(text = ''){ let input = document.createElement('input') input.style.position = 'fixed' input.style.top = '-10000px' input.style.zIndex = '-999' document.body.appendChild(input) input.value = text input.focus() input.select() try { let result = document.execCommand('copy') document.body.removeChild(input) if (!result || result === 'unsuccessful') { console.log('復制失敗') } else { console.log('復制成功') } } catch (e) { document.body.removeChild(input) alert('當前瀏覽器不支持復制功能,請檢查更新或更換其他瀏覽器操作') } }
完整代碼
function copyToClipboard(textToCopy) { // navigator clipboard 需要https等安全上下文 if (navigator.clipboard && window.isSecureContext) { // navigator clipboard 向剪貼板寫文本 return navigator.clipboard.writeText(textToCopy); } else { // document.execCommand('copy') 向剪貼板寫文本 let input = document.createElement('input') input.style.position = 'fixed' input.style.top = '-10000px' input.style.zIndex = '-999' document.body.appendChild(input) input.value = textToCopy input.focus() input.select() try { let result = document.execCommand('copy') document.body.removeChild(input) if (!result || result === 'unsuccessful') { console.log('復制失敗') } else { console.log('復制成功') } } catch (e) { document.body.removeChild(input) alert('當前瀏覽器不支持復制功能,請檢查更新或更換其他瀏覽器操作') } } }
所有問題都解決啦~
總結
以上就是關于js復制內容到瀏覽器剪貼板報錯:Cannot read properties of undefined (reading ‘writeText‘)的解決方案的詳細內容,更多關于js復制內容到瀏覽器剪貼板報錯的資料請關注腳本之家其它相關文章!
- js控制臺報錯Uncaught TypeError: Cannot read properties of undefined (reading ‘appendChild‘)的解決
- node.js報錯:Cannot find module ''ejs''的解決辦法
- JavaScript報錯:Uncaught TypeError: Cannot set property ‘X‘ of undefine的解決方案
- Node.js報錯信息Error:?Cannot?find?module?'XXX'問題及解決
- vue項目啟動后,js-base64依賴報錯Cannot read properties of null(reading ‘replace’)問題
- JavaScript中報錯Cannot?set?properties?of?undefined?(setting?‘1‘)解決方案
相關文章
一個JavaScript處理textarea中的字符成每一行實例
這篇文章主要與大家分享一個JavaScript處理textarea中的字符成每一行實例,很簡單,但很實用,大家可以看看2014-09-09