Capture keypress in Javascript (Google Docs)

自闭症网瘾萝莉.ら 提交于 2019-12-04 14:11:31

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!