[webkit-dev] Detecting paste with cmd-v on Mac

Rush Manbert rush at manbert.com
Tue Mar 3 12:21:17 PST 2009

I was testing some JavaScript code that a colleague wrote that does  
special handling when a user attempts to pastes a string into a text  
input box. He had developed it using Safari.

There s a routine that processes keyDown events. In it, he gets the  
charCode value from the keyEvent like this:
     var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ?  
evt.keyCode : ((evt.which ? evt.which : 0)));

After that, he checks for the WebKit browser, then does this:
         if(charCode == 86)
             return; // Don't mess around with the paste keyCode

This worked for Safari, but didn't work in my custom browser that uses  
WebKit. The difference is that in Safari, evt.charCode == 0, and  
evt.keyCode == 86, so charCode ends up with the value 86. However,  
when I use WebKit, I see evt.charCode == 118 and evt.keyCode == 86, so  
charCode ends up with the value of 118.

I checked the values of the DOM even modifiers alyKey, ctrlKey, and  
shiftKey and they are all false on a cmd-v paste

Further testing reveals that the code shown above cannot detect the  
difference between cmd-v and v, and detects shift-v as a cmd-v paste  
because evt.charCode == 86 in that case.

I tried to handle this by adding code that detects keyDown/keyUp and  
uses a state variable. I set it true when I see a keyDown event with  
evt.charCode == 91 and I set it false when I see a keyUp event with  
evt.charCode == 91. Then I check for the state variable true and  
charCode == 118 when I'm looking for a paste.

That seems to work for both WebKit and Safari.

Is there another way to handle this? Is the difference between Safari  
and WebKit expected?

- Rush

More information about the webkit-dev mailing list