![](/img/trans.png)
[英]document.execCommand('copy') Command not working in Chrome
[英]document.execCommand('copy') not working on Chrome
在 Chrome 上,只有document.execCommand('copy')
返回 true 但不復制文本,它會清除剪貼板。
我找不到任何有同樣問題的人,有很多類似的問題,但請不要將其標記為重復,除非確實如此。
selection.removeAllRanges()
之前調用selection.addRange()
。selection.getRangeAt(0).cloneContents()
返回包含正確文本的片段document.execCommand('copy')
textarea.select()
之前調用textarea.select()
文本顯示為選中狀態並被復制到剪貼板。 我不想這樣做,因為它聚焦 textarea 並導致頁面滾動。這是我的代碼(在單擊事件偵聽器中使用)
https://codepen.io/jakecr/pen/XVXvKz
var textarea = document.createElement('textarea');
textarea.textContent = 'coppied text';
document.body.appendChild(textarea);
var selection = document.getSelection();
var range = document.createRange();
range.selectNodeContents(textarea);
selection.removeAllRanges();
selection.addRange(range);
// DOESN'T WORK WITHOUT THIS
// textarea.select();
console.log(selection.getRangeAt(0).cloneContents());
console.log('copy success', document.execCommand('copy'));
我不太清楚這里到底發生了什么......
似乎在 textarea 的value
和textContent
屬性之間應該使用什么不匹配。
Chrome 似乎總是使用value
,而 Firefox 使用textContent
。
btn.onclick = e => { const txt = document.createElement('textarea'); document.body.appendChild(txt); txt.value = 'from value'; // chrome uses this txt.textContent = 'from textContent'; // FF uses this var sel = getSelection(); var range = document.createRange(); range.selectNode(txt); sel.removeAllRanges(); sel.addRange(range); if(document.execCommand('copy')){ console.log('copied'); } document.body.removeChild(txt); }
<button id="btn">Copy!</button> <textarea>You can paste here </textarea>
由於 chrome 不查看textContent
屬性,因此Range#selectNodeContents將在此瀏覽器上不選擇任何內容...
但是,您可以使用Range#selectNode在這種情況下應該返回相同的結果,並將解決該問題。
document.getElementById('btn').addEventListener('click', function(){ var textarea = document.createElement('textarea'); textarea.textContent = 'copied text'; document.body.appendChild(textarea); var selection = document.getSelection(); var range = document.createRange(); // range.selectNodeContents(textarea); range.selectNode(textarea); selection.removeAllRanges(); selection.addRange(range); console.log('copy success', document.execCommand('copy')); selection.removeAllRanges(); document.body.removeChild(textarea); })
<button id="btn">copy</button> <textarea>You can paste here</textarea>
對於在 2020 年閱讀此問題的人,如果您在使用document.execCommand('copy')
遇到問題,您可能想嘗試使用剪貼板 API。
每個Mozilla :
瀏覽器擴展可以通過兩種方式與系統剪貼板交互:Document.execCommand() 方法和現代異步剪貼板 API。
同樣根據Mozilla , document.execCommand()
現在已過時:
此功能已過時。 盡管它可能在某些瀏覽器中仍然有效,但不鼓勵使用它,因為它可以隨時被刪除。 盡量避免使用它。
使用剪貼板 API,將文本寫入剪貼板特別容易:
const textToCopy = 'Hello there!'
navigator.clipboard.writeText(textToCopy)
.then(() => { alert(`Copied!`) })
.catch((error) => { alert(`Copy failed! ${error}`) })
更多信息:
我發現您無法動態插入輸入字段,插入一些文本,然后將其復制到剪貼板。 我能夠從現有的輸入標簽復制文本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.