javascriptinternet-explorerfilteronpasteoncopy

Filter out HTML Tag onpaste for div and oncopy too


I have an editable DIV in my site to send a forum message. People can edit their messages (Bold, Italic, underline, add links and more)

But I want when some one paste or drop (- drop is not necessary, but paste it is) their text I want it to go in the DIV without HTML tags - clean, just text. (like if some one is going to word and make the text 200 points size, then copy & paste it in my DIV, they will have a very different message... and I don't want it to happen).

How can I scan the text coming from the clipboard to remove any HTML tags and then paste it in the DIV?

<html>
<head>
<script type="text/javascript" language="javascript">

function PasteFilter()
{
//windows.clipboardData filter on paste to go here
}

function CopyFilter()
{
//windows.clipboardData filter on copy to go here
}

</script>
</head>
    <body>
        <Div class="body" onpaste="PasteFilter()" oncopy="CopyFilter">
        <!-- div content goes here.-->
        </Div>
    </body>
    </html>

I would like to also apply the same filter with COPY too.

Thanks


Solution

  • I believe there are 2 ways to do this:

    1) The easy way - insert the following code in PasteFilter():

    var foo = window.clipboardData.getData('Text');
    window.clipboardData.setData('Text', foo);
    

    the first line gets the Text value of clipboardData (already stripped of HTML tags) and the second line sets the clipboardData to the plain text... (Tested on IE8)

    2) The other way - if for some reason that isn't suitable for you..

    In PasteFilter(), you trigger another function with a small delay timeout. In that function, you get the innerHTML contents of the DIV and run a regular expression to remove all tags.

    Example:

    function PasteFilter()
    {
        setTimeout('foo()', 200);
    }
    
    function foo()
    {
        var contents = document.getElementById("test").innerHTML;
    
        var new_contents = contents.replace(/(<([^>]+)>)/g, ""); // taken from http://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
    
        document.getElementById("test").innerHTML = new_contents;
    }
    

    The problem with this method is that you lose the caret position...

    Hope this helps...