Javascript keystroke capture (Google Docs)

I am trying to write a little greasemonkey script / bookmarklet / that you have for Google Docs. For the functionality that I would like to add, I need a keypress / keyup / keydown event handler (one of these three). Unfortunately, Javascript is not my fort, and I cannot capture (?) A keystroke event while in the edit panel. As a last resort, I 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, it still doesn't capture keystrokes in the edit panel - no annoying warnings (although it seems to work for most other sites ...). I checked both in Chrome and Firefox (I can't get it to work in one).

I tried Logging Events in Firebug (and checked all logged events through the neat little Firebug extension, Eventbug); it seemed that these events did not shoot the keys.

Edit:
To clarify [Tim], I took this screenshot with some annotations ... screenshot

The "edit panel" I'm talking about is a bunch of Javascript-up-divs displaying what I'm typing.

Any ideas? Thank!

+3
source share
3 answers

Google iframe. iframe. , - iframe, , Firefox :

var iframe = document.getElementsByTagName("iframe")[0];
if (iframe) {
    iframe.contentDocument.addEventListener("keypress", function(evt) {
        console.log("iframe keypress: " + evt.which);
    }, false);
}
+3

, ... jQuery $(document).ready(), , - . , javascript :

window.onload = function()
{
  els = document.getElementsByTagName("*");
  for(i=0;i<els.length;i++) {
    els[i].onkeypress=function(){alert("hello!");};
  }
}

, :

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!");};
}

( ), "alert (" hello3! ");"

0

. , .

window.addEventListener('load', function() {
    document.addEventListener('keypress', function() { alert("hello!"); });
}

Since this is a GreaseMonkey script, you do not need to worry about IE and use the method addEventListener.

0
source

Source: https://habr.com/ru/post/1778897/


All Articles