簡體   English   中英

可以將剪貼板文本/html mimetype 復制到 javascript 中的文本/純文本嗎?

[英]Possible to copy Clipboard text/html mimetype to text/plain in javascript?

假設我有從復制到剪貼板事件(例如document.execCommand )生成的text/html

有沒有辦法將該數據復制到text/plain mimetype 中而不會丟失text/html數據? 如果是這樣,如何做到這一點? 請注意,我當前在復制剪貼板中有 text/html 數據,不能同時寫入兩者。

最好的可能是直接在復制時處理它。 由於text/html應該只在從 Selection 復制而不是從輸入復制時設置,我們可以通過 Range API 獲取標記,並覆蓋我們復制事件的數據。

 addEventListener( "copy", (evt) => { const selection = getSelection(); if( selection.isCollapsed ) return; evt.preventDefault(); const range = selection.getRangeAt(0); const data_as_html = new XMLSerializer().serializeToString( range.cloneContents() ); evt.clipboardData.setData("text/plain", data_as_html); evt.clipboardData.setData("text/html", data_as_html); } );
 <p> <span style="color:red;font-weight:bold">copy</span><span style="color:green;font-weight:thinner"> this</span> <span style="color:blue"> text</span> </p> <div contenteditable>Paste here as rich-text</div> <textarea cols="30" rows="10">Paste here as markup</textarea>

現在OP說他們當時不能這樣做,因為我不知道是什么原因。
這意味着他們需要能夠讀取剪貼板的內容,為此,他們需要用戶的批准,或者通過剪貼板 API 的權限,或者通過處理"paste"事件。

但是,似乎沒有瀏覽器真正支持從剪貼板 API 中讀取plain/text以外的任何內容,這讓我們只剩下粘貼事件:

 btn.onclick = (evt) => { addEventListener( "paste", (evt) => { const data_as_html = evt.clipboardData.getData("text/html"); if( data_as_html ) { } addEventListener("copy", (evt) => { evt.preventDefault(); evt.clipboardData.setData("text/plain", data_as_html); evt.clipboardData.setData("text/html", data_as_html); }, { once: true } ); document.execCommand("copy"); }, { once: true } ); document.execCommand("paste"); }
 <button id="btn">convert clipboard content to markup</button><br> <p> <span style="color:red;font-weight:bold">copy</span><span style="color:green;font-weight:thinner"> this</span> <span style="color:blue"> text</span> </p> <div contenteditable>Paste here as rich-text</div> <textarea cols="30" rows="10">Paste here as markup</textarea>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM