?
Solved

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

Posted on 2014-04-29
4
Medium Priority
?
1,222 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 33

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 33

Accepted Solution

by:
Big Monty earned 2000 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

Give Your Engineering Team a Productivity Boost

Learn why container technology is so powerful and how it can provide your team with productivity gains and other benefits.

Question has a verified solution.

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

Does your audience prefer people in photos or no people? How can you best highlight what you’re selling? What are your competitors doing, and what can you do that is different and unique from them?  Continue reading to learn how to make your images …
Originally, this post was published on Monitis Blog, you can check it here . It goes without saying that technology has transformed society and the very nature of how we live, work, and communicate in ways that would’ve been incomprehensible 5 ye…
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

777 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