问题
I'm running into an issue with a small Chrome extension that I'm writing. Basically the issue is that I need to simulate a keydown event in an input field so that the targeted site will pick it up with its listener.
To find the listeners I set an Event Listener Breakpoint for all Keyboard events then typed into the input field. There were 3 breakpoints that I had to step through, all for Keyboard->keydown events. Here's the basic info for them:
Arguments: Arguments[1]
E: KeyboardEvent
This: input#header-search.form-control
Arguments: Arguments[1]
E: KeyboardEvent
This: document
Arguments: Arguments[1]
E: KeyboardEvent
This: Window
I have tried using keyboardevents with no luck, perhaps I just haven't done them correctly (it's hard finding documentation for keyboardevents in Chrome) or maybe I need to go another route. Any help would be greatly appreciated, thanks!
回答1:
You need to fire the events in the context of the web page your extension works with. Here is what works for me.
- Inject jQuery in the web page.
- I'm using this jQuery extension: https://github.com/jquery/jquery-simulate Inject this in the web page as well.
- Before injecting the scripts I am renaming all $ occurrences with jQuery the reason being not to create conflicts with the web page scripts.
You can inject the scripts using the following pattern (there are other ways of injecting js):
Add the following function in the content script of your extension
function injectJQuery() {
var s = document.createElement('script');
s.textContent = '(' + function() {
//paste jQuery plugin here
} + ')()';
}
Then same pattern for injecting simulate extension
function injectJQuerySimulate() {
var s = document.createElement('script');
s.textContent = '(' + function() {
//paste jQuery simulate plugin here
} + ')()';
}
When your extension's content script runs call this two functions once in order to inject the scripts in the web page.
Now you can send keydown events with the jQuery simulate plugin to the web page using the following function:
function sendKeydown(elemId, keyCode) {
var s = document.createElement('script');
s.textContent = '(' + function(elemId, keyCode) {
jQuery(elemId).simulate('keydown', {
keyCode: keyCode
});
} + ')("' + elemId + '", "' + keyCode + '");';
(document.head || document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
}
Example use:
sendKeydown('#SomeElementId', 37); //37 is the keyCode for left arrow key
Reference table for the ASCII key codes: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
来源:https://stackoverflow.com/questions/32078839/javascript-in-chrome-extension-creating-keydown-event