TinyMCE as comment editor – encoding issues

It’s still unclear to me why this is happening, because all the encoding of < and > for comments looks the same as posts do in the database view, so I’m still unsure why TinyMCE is treating post_content vs comment_content differently. But ultimately, all that needs to happen is for the existing escaped HTML tags to get decoded when editing on the backend.

jQuery( document ).on( 'tinymce-editor-init', function( event, editor ) {
    function htmlDecode(input) {
        var doc = new DOMParser().parseFromString(input, "text/html");
        return doc.documentElement.textContent;
    }

    function fixTinyMCEComments() {
        var parent = document.querySelector("#content_ifr").contentDocument.children[0].querySelector("#tinymce");
        Array.from(parent.children).forEach(function(p) {
            p.innerHTML = htmlDecode(p.innerHTML);
        });
    }

    fixTinyMCEComments();
});

Register it wherever your admin_enqueue_scripts is called in functions.php – I enqueue it only on comment.php:

// Enable TinyMCE as the backend comments editor
function load_backend_comments_editor( $settings, $id ){
    global $pagenow; 
    if ( $id == 'content' && $pagenow === 'comment.php' ){
        $settings['tinymce'] = true;
        wp_enqueue_script( 'mytheme-admin' );
    }
    return $settings;
}
add_filter( 'wp_editor_settings', 'load_backend_comments_editor', 10, 2 );

This is a bit of a hack, because the implementation depends on TinyMCE maintaining its current node tree, but since this is on the backend for something that likely won’t continue to be edited after a month or so, I’m okay with it. Any improvements are welcome, though!