Intercept paste event in Javascript

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.

Leave a Comment