Chrome extension: how to send a "keydown" event to a page tab?

I have a test web page that warns me if I press a key in the input field:

<!doctype html> <html> <head> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> <script> $( document ).ready( function() { $( '#foo' ).keydown( function() { alert( "debug" ); } ); }); </script> </head> <body> <input id='foo' type='type'/> </body> </html> 

And I have this chrome extension that changes the input text and fires the keydown event:

 $( document ).ready( function() { window.setTimeout( function() { $( '#foo' ).val( "foo" ); $( '#foo' ).keydown(); }, 2000 ); }); 

If I install the extension, after 2 seconds (as expected) the text changes, but the warning does not appear, so I can assume that the keydown event keydown not being sent from the extension sandbox to the javascript JavaScript handler. Is there any way I can change my code so that the extension can emulate keydown that javascript can see on the page? I am automating a third-party website using the chrome extension, and one of the inputs requires keyup to detect a value change (page automation I am poorly written - but I have no control over other source code).

0
google-chrome-extension
source share
1 answer

Your code does not work because the jQuery keydown() method does not actually keydown() "real" keydown event. Instead, jQuery scans the "related" event handlers in jQuery.cache and calls the corresponding functions.

Since your jQuery script content is different from the jQuery object of the page, calling .keydown() does not cause any action.

In your case, I suggest entering the code on the page so that your code works in the same context as the page. Then calling $('#foo').keydown() will use the jQuery object of the page and lead to the expected behavior.

A general solution that is independent of any library is to use the KeyboardEvent constructor ( defined in DOM4 ) to fire an event:

 var event = new KeyboardEvent('keydown'); document.querySelector('#foo').dispatchEvent(event); 
+8
source share

All Articles