Skip to content

Commit 41e2da8

Browse files
puredazzlevinkla
andauthored
Strip all HTML tags except those we have whitelisted on paste (#20)
* Strip all HTML tags except those we have whitelisted on paste When a user pastes text from another website into the TinyMCE editor, excessive HTML tags are added. This PR removes all HTML tags except those specified in the whitelist. * Update headache.php * Update headache.php Co-authored-by: Vincent Klaiber <[email protected]> * Allow li --------- Co-authored-by: Vincent Klaiber <[email protected]>
1 parent 174ef25 commit 41e2da8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

headache.php

+31
Original file line numberDiff line numberDiff line change
@@ -283,3 +283,34 @@ function disable_indexing()
283283
}
284284

285285
add_action('pre_option_blog_public', __NAMESPACE__ . '\\disable_indexing');
286+
287+
// Sanitize HTML content when pasting in TinyMCE editor.
288+
function sanitize_tiny_mce_html_content(array $config): array
289+
{
290+
$config['paste_preprocess'] = "function(plugin, args) {
291+
// Allow specific HTML tags while sanitizing the content
292+
const allowedTags = new Set(['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'p', 'ol', 'ul', 'li', 'a']);
293+
const sanitizedContent = document.createElement('div');
294+
sanitizedContent.innerHTML = args.content;
295+
296+
// Remove elements not in the allowed tags
297+
sanitizedContent.querySelectorAll('*').forEach(element => {
298+
if (!allowedTags.has(element.tagName.toLowerCase())) {
299+
element.replaceWith(...element.childNodes); // Replace with child nodes
300+
}
301+
});
302+
303+
// Strip class and id attributes
304+
sanitizedContent.querySelectorAll('*').forEach(element => {
305+
element.removeAttribute('id');
306+
element.removeAttribute('class');
307+
});
308+
309+
// Return the clean HTML
310+
args.content = sanitizedContent.innerHTML;
311+
}";
312+
313+
return $config;
314+
}
315+
316+
add_filter('tiny_mce_before_init', __NAMESPACE__ . '\\sanitize_tiny_mce_html_content');

0 commit comments

Comments
 (0)