问题
I'm trying to write a little greasemonkey script/bookmarklet/what have you for Google Docs. The functionality I'd like to add needs a keypress/keyup/keydown event handler (one of those three). Unfortunately, Javascript isn't my forté, and I can't seem to capture (?) a keypress event to while in the edit pane. As a last resort, I've tried the following:
javascript:(function(){
els = document.getElementsByTagName("*");
for(i=0;i<els.length;i++){
els[i].onkeypress=function(){alert("hello!");};
els[i].onkeyup=function(){alert("hello2!");};
els[i].onkeydown=function(){alert("hello3!");};
}
})();
However, this still doesn't capture keypresses in the editing pane - no annoying alerts (although it seems to work for most other sites...). I've checked in Chrome and Firefox both (I can't get it to work in either one).
I tried "Log Events" in Firebug (and checked out all the registered events via a neat little extension to Firebug, Eventbug); it didn't seem like those events were firing on keypresses.
Edit:
To clarify [Tim], I made this screenshot with some annotations...

The "editing pane" I'm talking about seems to be a bunch of Javascripted-up divs displaying what I type.
Any ideas? Thanks!
回答1:
Editing in Google Docs uses an iframe. You need to attach a listener to the iframe's document. It seems to do something complicated with the iframe I haven't yet been able to work out fully, but the following seems to work for Firefox:
var iframe = document.getElementsByTagName("iframe")[0];
if (iframe) {
iframe.contentDocument.addEventListener("keypress", function(evt) {
console.log("iframe keypress: " + evt.which);
}, false);
}
回答2:
Seems to work for me... but I'm using jQuery $(document).ready() to make sure my page is loaded before attaching any event. I think you could do it in bare javascript with :
window.onload = function()
{
els = document.getElementsByTagName("*");
for(i=0;i<els.length;i++) {
els[i].onkeypress=function(){alert("hello!");};
}
}
By the way you can't attach more than one function to the event:
for(i=0;i<els.length;i++){
els[i].onkeypress=function(){alert("hello!");};
els[i].onkeypress=function(){alert("hello2!");};
els[i].onkeypress=function(){alert("hello3!");};
}
The element will register only the last one (it overrides the previous function), in this case "alert("hello3!");"
回答3:
You do not need to attach the listener to all the elements on the page. To attach it to the document is enough.
window.addEventListener('load', function() {
document.addEventListener('keypress', function() { alert("hello!"); });
}
Since it is a GreaseMonkey script you do not need to worry about IE and can use the addEventListener
method.
来源:https://stackoverflow.com/questions/4373666/capture-keypress-in-javascript-google-docs