I have a test web page that alerts if i hit a key in it\'s input field:
Your code is not working because jQuery's keydown()
method does not actually trigger a "real" keydown event. Instead, jQuery looks up the "bound" event handlers in jQuery.cache
, and calls the corresponding functions.
Since your content script's jQuery
object differs from the page's jQuery
object, invoking .keydown()
doesn't cause any action.
In your case, I suggest to inject your code in the page, so that your code runs in the same context as the page. Then, calling $('#foo').keydown()
will use the page's jQuery object, and result in the expected behaviour.
A general solution, which doesn't depend on any library is to use the KeyboardEvent
constructor (defined in DOM4) to trigger the event:
var event = new KeyboardEvent('keydown');
document.querySelector('#foo').dispatchEvent(event);