iT邦幫忙

0

div 的 contenteditable ,黏貼內容時,可將含有 HTML 的標籤清除,僅留下純文字?

  • 分享至 

  • twitterImage

事由
div 的 contenteditable 功能,可以複製 HTML 進去也會被接受,假如,我複製了SF某個文章貼到這個 div 中,SF原本的HTML 標籤都會被複製上去。

代碼

<div contenteditable=true"></div>

問題

  1. 不知道 js,jquery 能用什麼函數可以實現:當我複製的內容中若含有 HTML 標籤,則自動將其 tag 清空,僅留下純文字?
  2. 假設複製的內容中,有 <iframe src*=instagram (或是有 <iframe>)的標籤,則維持原樣不清空,將其它的 HTML 標籤tag 清空,僅留下純文字,然後再貼到 div 中?
froce iT邦大師 1 級 ‧ 2018-09-22 15:02:31 檢舉
https://www.w3schools.com/jsref/event_onpaste.asp
或許可以從這個事件去著手
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
froce
iT邦大師 1 級 ‧ 2018-09-22 18:09:45
最佳解答

解釋一下思路:
1.不可能從複製的地方下手,因為複製來源不可能一定是網頁,也不一定是你的網頁。
2.js不可能直接去改本機電腦剪貼簿資料,因為會有資安問題。
3.所以只能從貼上的時候去做,而且這樣可以確定貼上時,可以對特定區域改變貼上文字。

https://jsbin.com/pohozexaso/1/edit?html,console,output
https://stackoverflow.com/questions/11605415/jquery-bind-to-paste-event-how-to-get-the-content-of-the-paste
剩下的tag處理得自己來,因為不一定剪貼簿裡的文字有tag。

1
DanSnow
iT邦好手 1 級 ‧ 2018-09-23 21:11:48

處理掉 tag 我有個做法 主要是讓瀏覽器去 parse html 然後再用 textContent 取出文字部份 這個方式就算原本沒有 tag 也不會出問題

const html = `
<div>
  <img src="foo.png">
  <p>Paragraph</p>
  <div>In div</div>
</div>
`
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
console.log(doc.documentElement.textContent)

https://codepen.io/dododavid006/pen/bxJMPX?editors=0011

Edit:
沒注意到要保留 iframe 思路是找最近的文字內容 在清掉所有 tag 後把 iframe 插回去
不過如果有連續的 iframe 可能會發生兩個 iframe 的順序倒過來

const html = `
<div>
  <iframe id="frame2"></iframe>
  <img src="foo.png">
  <p>Paragraph</p>
  <div>In div</div>
  <iframe id="frame1"></iframe>
</div>
`
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
const iframes = new Map()
Array.from(doc.querySelectorAll('iframe')).forEach(iframe => {
  let $el = iframe.previousSibling
  while($el) {
    if ($el.textContent.trim()) {
      iframes.set($el.textContent, iframe.outerHTML)
      return
    }
    $el = $el.previousSibling
  }
  iframes.set(/^/, iframe.outerHTML)
})
let text = doc.documentElement.textContent
iframes.forEach((code, insertPoint) => {
  text = text.replace(insertPoint, (insertPoint instanceof RegExp ? code : insertPoint + code))
})
console.log(text)

Edit2:
如果要比較完整的支援可以用 https://github.com/punkave/sanitize-html

froce iT邦大師 1 級 ‧ 2018-09-23 21:36:15 檢舉

他還要iframe不能被過濾掉,這樣不知道會不會被過濾?

DanSnow iT邦好手 1 級 ‧ 2018-09-23 21:51:18 檢舉

糟糕 沒注意到 我想會的 iframe 應該要另外處理

DanSnow iT邦好手 1 級 ‧ 2018-09-23 22:13:54 檢舉

剛剛更新了處理 iframe 的部份

我要發表回答

立即登入回答