我正在尝试使用React网站上的Chrome扩展程序发送按键输入,但无法让它工作。以下是在google.com上输入“a”的代码片段
我的基础是Firing a keyboard event on Chrome的答案 它不起作用。
function createKeyboardEvent (aType, aTarget, aKeyCode, opt_keyModifiers) {
var mods, match, domEvent;
mods = (opt_keyModifiers == null) ? '' : opt_keyModifiers;
match = /\[(.*)\]/.exec(aKeyCode);
var keyCode, charCode, which;
var key = String.fromCharCode(aKeyCode).toLowerCase();
keyCode = aKeyCode;
which = aKeyCode;
charCode = 0;
domEvent = new window.KeyboardEvent(aType, {
bubbles: true,
cancelable: true,
ctrlKey: mods.indexOf('ctrlKey') !== -1,
altKey: mods.indexOf('altKey') !== -1,
shiftKey: mods.indexOf('shiftKey') !== -1,
metaKey: mods.indexOf('metaKey') !== -1,
key: key,
charCode: 0,
which: keyCode,
keyCode: keyCode,
codeVal: "KeyA",
view: window
});
// Chromium Hack. With Chrome 43, our setting of keycode and
// charcode was deprecated.
Object.defineProperty(domEvent, 'keyCode', {
get : function() {
return this.keyCodeVal;
}
});
Object.defineProperty(domEvent, 'which', {
get : function() {
return this.whichVal;
}
});
Object.defineProperty(domEvent, 'charCode', {
get : function() {
return this.charCodeVal;
}
});
Object.defineProperty(domEvent, 'key', {
get : function() {
return this.keyVal;
}
});
Object.defineProperty(domEvent, 'code', {
get : function() {
return this.codeVal;
}
});
domEvent.charCodeVal = charCode;
domEvent.keyCodeVal = keyCode;
domEvent.whichVal = which;
domEvent.keyVal = key;
domEvent.codeVal = "KeyA";
aTarget.dispatchEvent(domEvent);
}
// Type 'a'
var target = document.getElementById('lst-ib');
target.focus();
var nextKeyCode = 65;
createKeyboardEvent('keydown', target, nextKeyCode);
createKeyboardEvent('keypress', target, nextKeyCode);
createKeyboardEvent('keyup', target, nextKeyCode);