Detect pasted text with Ctrl+v or right click -> paste

You could use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths and to know where to look for the pasted content. Something like the following. For the sake of brevity, the function that gets the textarea selection does not work in IE. See here for something that does: How to get the start and end points of selection in text area?

function getTextAreaSelection(textarea) {
    var start = textarea.selectionStart, end = textarea.selectionEnd;
    return {
        start: start,
        end: end,
        length: end - start,
        text: textarea.value.slice(start, end)
    };
}

function detectPaste(textarea, callback) {
    textarea.onpaste = function() {
        var sel = getTextAreaSelection(textarea);
        var initialLength = textarea.value.length;
        window.setTimeout(function() {
            var val = textarea.value;
            var pastedTextLength = val.length - (initialLength - sel.length);
            var end = sel.start + pastedTextLength;
            callback({
                start: sel.start,
                end: end,
                length: pastedTextLength,
                text: val.slice(sel.start, end)
            });
        }, 1);
    };
}

var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
    alert(pasteInfo.text);
    // pasteInfo also has properties for the start and end character
    // index and length of the pasted text
});

HTML5 already provides onpaste not only <input/> , but also editable elements (<p contenteditable="true" />, ...)

<input type="text" onpaste="myFunction()" value="Paste something in here">

More info here


Quite an old thread, but you might now use http://willemmulder.github.com/FilteredPaste.js/ instead. It will let you control what gets pasted into a textarea or contenteditable.

Tags:

Javascript