javascriptjqueryhtmltinymce-4

TinyMCE Sanitizing input


I'm trying to use TinyMCE (version 4.1.2) as a WYSIWYG editor. Logged in users can write their own pages and see directly what will be shown on the page when a visitor visits.

Now, I'd like for the html to be stored directly. For example:

The logged in user sees This is my text!, but in fact TinyMCE displays it as <p>This is my text!</p>. There's also certain styles like a <h1> and links that can be added.

Now, a user can insert a hyperlink, giving the link and text that should be displayed. Problem is however, if a user manually write <a href='example.com'>Example</a>, it shows in the editor like so but gets stored in pure html as well, so when displaying it will just be a hyperlink with the text Example.

This is how my code sort of looks like (left out configuration):

tinymce.init({
    setup: function(editor){
        editor.on('change', function(e){
            $('[name="'+editor.id+'"]').next("textarea").html(editor.getContent({format: 'html'}));
        });
    }
});

So the text from the TinyMCE field gets copied into a <textarea> that is inside a <form> which gets submitted when saving.

Something like this:

TinyMCE input of user

gets stored as:

<h1>Title</h1>
<p><a href="example.com">example</a></p>
<p><a href="example.com">test</a></p>

Which leaves me no way to distinguish genuine links and pure text, so I can't process it after the storing of the data.

I've already fiddled around with the editor.getContent({format: 'html'}) format options, like format: 'raw', but with no avail. What am I doing wrong?


Solution

  • Hopefully i'm understanding your question correctly.

    It looks like you're wanting to display whatever your user inputs EXACTLY as they input it without actually processing whatever HTML the user wrote in as HTML. Am I correct? I believe this addresses the issue you're having:

    https://kokoblog.net/php/fix-tinymce-auto-convert-html-code-to-element-tag

    However, if you're only concerned about how it looks where it's stored, and not how it looks when it's processes then you'll want to add code blocks to tinyMCE and make sure your users understand that they need to select the code option whenever they're going to write raw HTML.

        style_formats : [{title : 'Code', inline : 'code'}]
    

    src: Add "code" button to wordpress tinyMCE

    I hope this helps! :)