Created
January 18, 2012 03:57
-
-
Save endtwist/1630834 to your computer and use it in GitHub Desktop.
Paste event in Google Chrome
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$( '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
Nice catch. Thanks!