Skip to content

Instantly share code, notes, and snippets.

@endtwist
Created January 18, 2012 03:57
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save endtwist/1630834 to your computer and use it in GitHub Desktop.
Save endtwist/1630834 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?
} );
@franzenzenhofer
Copy link

evt.originalEvent.clipboardData(item.type)

should be

evt.originalEvent.clipboardData.getData(item.type)

@endtwist
Copy link
Author

Nice catch. Thanks!

@Integralist
Copy link

I'm using Google Chrome 17.0.963.79 and neither e.originalEvent.clipboardData.items or e.originalEvent.clipboardData.getData(item.type) work.

I can access data via e.clipboardData.items but not the same structure of data as you suggest in your code snippet...

@PleaseTryAgain
Copy link

I have the same proplem with you @Integralist . do you solve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment