Intercept paste event in Javascript

Is there a way to intercept the paste event in JavaScript and get the raw value, change it, and set the associated DOM element's value to be the modified value?

For instance, I have a user trying to copy and paste a string with spaces in it and the string's length exceeds the max length of my text box. I want to intercept the text, remove the spaces, and then set the text box's value with the change value.

Is this possible?


Solution 1:

You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.

For example:

var myElement = document.getElementById('pasteElement');
myElement.onpaste = function(e) {
  var pastedText = undefined;
  if (window.clipboardData && window.clipboardData.getData) { // IE
    pastedText = window.clipboardData.getData('Text');
  } else if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/plain');
  }
  alert(pastedText); // Process and handle text...
  return false; // Prevent the default handler from running.
};

As @pimvdb notes, you will need to use "e.originalEvent.clipboardData" if using jQuery.

Solution 2:

As it happens, I answered a similar question earlier today. In short, you need a hack to redirect the caret to an off-screen textarea when the paste event fires.

Solution 3:

$(document).ready(function() {
    $("#editor").bind('paste', function (e){
        $(e.target).keyup(getInput);
    });

    function getInput(e){
        var inputText = $(e.target).val();
        alert(inputText);
        $(e.target).unbind('keyup');
    }
});

Solution 4:

I needed to implement a "trim" on whatever was pasted (remove all leading and trailing whitespace) while still allowing the use of the spacebar.

For Ctrl+V, Shift+Insert and mouse right-click Paste, here is what I found worked in FF, IE11 and Chrome as of 2017-04-22:

$(document).ready(function() {
    var lastKeyCode = 0;

    $('input[type="text"]').bind('keydown', function(e) {
        lastKeyCode = e.keyCode;
    });
    // Bind on the input having changed.  As long as the previous character
    // was not a space, BS or Del, trim the input.
    $('input[type="text"]').bind('input', function(e) {
        if(lastKeyCode != 32 && lastKeyCode != 8 && lastKeyCode != 46) {
            $(this).val($(this).val().replace(/^\s+|\s+$/g, ''));
        }
    });
});

Two caveats:

  1. If there is already text when the paste occurs, trimming occurs on the entire result, not just what it being pasted.

  2. If the user types space or BS or Del and then pastes, trimming will not occur.