[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2014-04-29
4
Medium Priority
?
1,265 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 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: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 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:jwleys
ID: 40033411
Thank you, this was the best solution for me :)
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
Dramatic changes are revolutionizing how we build and use technology. Every company is automating, digitizing, and modernizing operations. We need a better, more connected way to work together as teams so we can harness the insights from our system…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
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
Course of the Month20 days, 6 hours left to enroll

873 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