Skip to content

Instantly share code, notes, and snippets.

@franzenzenhofer
Forked from endtwist/gist:1630834
Created February 22, 2012 04:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franzenzenhofer/1881270 to your computer and use it in GitHub Desktop.
Save franzenzenhofer/1881270 to your computer and use it in GitHub Desktop.
Paste event in Google Chrome
$( 'body' ).bind( 'paste', function( evt ) {
var items = evt.originalEvent.clipboardData.items
, paste;
// Items have a "kind" (string, file) and a MIME type
console.log( 'First item "kind":', items[0].kind );
console.log( 'First item MIME type:', items[0].type );
// If a user pastes image data, there are 2 items: the file name (at index 0) and the file (at index 1)
// but if the user pastes plain text or HTML, index 0 is the data with markup and index 1 is the plain, unadorned text.
if( items[0].kind === 'string' && items[1].kind === 'file' && items[1].type.match( /^image/ ) ) {
// If the user copied a file from Finder (OS X) and pasted it in the window, this is the result. This is also the result if a user takes a screenshot and pastes it.
// Unfortunately, you can't copy & paste a file from the desktop. It just returns the file's icon image data & filename (on OS X).
item = items[0];
} else if( items[0].kind === 'string' && items[1].kind === 'string' ) {
// Get the plain text
item = items[1];
}
// From here, you can use a FileReader object to read the item with item.getAsFile(), or evt.originalEvent.clipboardData.getData(item.type) to get the plain text. Confused yet?
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment