简体   繁体   中英

javascript keydown event does not work when the focus is a gmail writing input

I'm trying to make a chrome extension with javascript which triggers an action on key presses when I'm typing an email in gmail.

I manage to make the extension, which performs a console log correctly when I press the keys on any page.

My problem comes when capturing the event when I am typing in a gmail email writing input, it doesn't capture the event.

The body text box is a contenteditable div, and the from and subject text boxes are inputs. I don't know if this helps

The JS code I inject is as follows:

document.addEventListener('keydown', function (e){
  console.log('push')
});

The code works in the search input of the page but not in the write input of the email. Does anyone know why?

Using document.addEventListener is probably not the right way to go when adding event listeners.

There's a 90% chance that the keydown event is being directly handled by the contenteditable div and the input elements which prevents it from being handled by the document itself. You may need to attach the event listener directly to the contenteditable div and the input elements (referencing them in some way or another - you can take a look at how MailTrack or some Gmail extension to see how they do it), rather than the document.

You can try opening up inspect element and seeing if the classes or IDs change, and make a decision on how to hook them up to your code using those; and attaching the appropriate event listener to them.

You can also try using event delegation to attach the appropriate event listener to a parent element of the input and contenteditable div ; then check the event target to see if it is the element you are interested in - but I won't get into that since it's probably not the best approach to this type of situation.

It's entirely possible - since if another chrome extension can do it, yours can probably do it as well. It just comes down to information collection and the appropriate research.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM