Restrict paste in contenteditable (HTML / JS)

2019-04-28 23:38发布

问题:

I would like to prevent the user from pasting non allowed markup in a contenteditable div.

I would like to restrict paste to bold, italic, strike, underline and links.

What is the best way (I'm using jQuery) ?

This is not a duplicate of JQuery Text Editor Paste Without Formatting. I don't want to paste without formatting. I want to select / restrict to some markups.

I already read the following questions, none provides a clear answer:

  • JQuery Text Editor Paste Without Formatting
  • How to filter user pasted content in contenteditable div?
  • Javascript trick for 'paste as plain text` in execCommand
  • Contenteditable allowing only plain text

回答1:

Restrict pasted content by listening to the editable element's paste event. Inside this event, you can filter the data the user is attempting to paste by using a regular expression.

const el = document.querySelector('p');

el.addEventListener('paste', (e) => {
  // Get user's pasted data
  let data = e.clipboardData.getData('text/html') ||
      e.clipboardData.getData('text/plain');
  
  // Filter out everything except simple text and allowable HTML elements
  let regex = /<(?!(\/\s*)?(a|b|i|em|s|strong|u)[>,\s])([^>])*>/g;
  data = data.replace(regex, '');
  
  // Insert the filtered content
  document.execCommand('insertHTML', false, data);

  // Prevent the standard paste behavior
  e.preventDefault();
});
<p contenteditable>Try pasting content into this paragraph. The pasted content can include a <b>BOLD</b>, <i>ITALIC</i>, <s>STRIKE</s>, or <u>UNDERLINE</u>. It can also include a <a href='#'>LINK</a>.</p>