?
Solved

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

Posted on 2014-04-29
4
Medium Priority
?
1,289 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:Jeremy Leys
  • 2
  • 2
4 Comments
 
LVL 34

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:Jeremy Leys
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 34

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:Jeremy Leys
ID: 40033411
Thank you, this was the best solution for me :)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
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)
Suggested Courses

588 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