Solved

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

Posted on 2014-04-29
4
1,190 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 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

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

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

Because your company can’t afford for you to make SEO mistakes, you’ll want to ensure you’re taking the right steps each and every time you post a new piece of content. This list of optimization do’s and don’ts can help you become an SEO wizard.
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. 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.: (CODE)

690 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