Solved

How do I javascript force paste as plain text cross browser?

Posted on 2014-04-29
4
1,095 Views
Last Modified: 2014-04-30
Hi,

I am using TinyMCE version 4.06, I am having problems with customers pasting both HTML and other other rich text formatting junk into the TinyMCE editor. One of my customers pasted a paragraph with an opening div and no closing div. I am stripping bad formatting and characters server-side. The main issue I am having is that browsers such as IE8 don't handle malformed HTML well, so if customers paste divs that don't close or any malformed junk, TinyMCE will not display anything for them in the editor yet if you look in a modern browser you can see the content in TinyMCE.

What I want is a solution that works cross browser for forcing a client-side paste as plain text, failing that a solution that works for IE8 and above would suffice as Chrome, Firefox, Opera and Safari appear to have no problems.

My TinyMCE initialize function:

// Strips HTML and PHP tags from a string 
// returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
// example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
// returns 2: '<p>Kevin van Zonneveld</p>'
// example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
// returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
// example 4: strip_tags('1 < 5 5 > 1');
// returns 4: '1 < 5 5 > 1'
function strip_tags (str, allowed_tags)
{

    var key = '', allowed = false;
    var matches = [];    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = ''; 
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    // Build allowes tags associative array
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
    }
    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
                // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();
        // Is tag not in allowed list? Remove from str!
        allowed = false;

        // Go through all allowed tags
        for (k in allowed_array) {            // Init
            allowed_tag = allowed_array[k];
            i = -1;

            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}

            // Determine
            if (i == 0) {                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); // Custom replace. No regexing
        }
    }
    return str;
}

tinymce.init({
	selector: 'textarea:not(.mceNoEditor)',
	toolbar: 'undo redo | bold italic | bullist numlist',
	menubar : false,
	force_br_newlines : false,
	force_p_newlines : false,
	forced_root_block : '',
	editor_deselector : "mceNoEditor",
	plugins : "paste",
	paste_use_dialog : false,
	paste_auto_cleanup_on_paste : true,
	paste_convert_headers_to_strong : false,
	paste_strip_class_attributes : "all",
	paste_remove_spans : true,
	paste_remove_styles : true,
	paste_retain_style_properties : "",
	paste_preprocess : function(pl, o) {
		//example: keep bold,italic,underline and paragraphs
		//o.content = strip_tags( o.content,'<b><u><i><p>' );

		// remove all tags => plain text
		o.content = strip_tags( o.content,'' );
	},
	paste_text_sticky : true,
	oninit: function (ed) {
        ed.pasteAsPlainText = true;
    }
});

Open in new window

0
Comment
Question by:jwleys
  • 2
  • 2
4 Comments
 
LVL 32

Expert Comment

by:Big Monty
ID: 40032211
i think you want to add in

config.forcePasteAsPlainText = true;

in your editor initialization. I'm not sure how well it handles html tags though

http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.forcePasteAsPlainText
0
 

Author Comment

by:jwleys
ID: 40032960
Correct me if I am wrong and if it is cross compatible, isn't that documentation for CKEDITOR? I am using TinyMCE, is that config available for TinyMCE?
0
 
LVL 32

Accepted Solution

by:
Big Monty earned 500 total points
ID: 40032989
yup, you're right, my mistake on that. have a look at this blog to get this functionality in tinyMCE. as long as you don't have to support opera, this should work:

http://www.abeautifulsite.net/blog/2008/10/forcing-paste-as-plain-text-in-tinymce/
0
 

Author Closing Comment

by:jwleys
ID: 40033411
Thank you, this was the best solution for me :)
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
The is a quite short video tutorial. In this video, I'm going to show you how to create self-host WordPress blog with free hosting service.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now