是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
你可以用下面的代码模拟输入密码:
铬测试100%工作
DoCustomEvent('password', '#loginpin');
function DoCustomEvent(ct, elem){
var key;
var pressEvent = document.createEvent("CustomEvent");
pressEvent.initCustomEvent("keypress", true, false);
for (var i =0; i < ct.length; ++i)
{
key = ct.charCodeAt(i);
pressEvent.bubbles = true;
pressEvent.cancelBubble = false;
pressEvent.returnValue = true;
pressEvent.key = ct.charAt(i);
pressEvent.keyCode = key;
pressEvent.which = key;
pressEvent.charCode = key;
pressEvent.shiftKey = false;
pressEvent.ctrlKey = false;
pressEvent.metaKey = false;
document.querySelector(elem).focus();
//keypress //beforeinput //input //sendkeys //select
setTimeout(function() {
var e = new window.KeyboardEvent('keypress', pressEvent);
document.activeElement.dispatchEvent(e);
e = new window.KeyboardEvent('input', pressEvent);
document.activeElement.dispatchEvent(e);
}, 0);
document.querySelector(elem).value = document.querySelector(elem).value + ct.charAt(i);
}
其他回答
一个非jquery版本,工作在webkit和gecko:
var keyboardEvent = document.createEvent('KeyboardEvent'); var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? 'initKeyboardEvent' : 'initKeyEvent'; keyboardEvent[initMethod]( 'keydown', // event type: keydown, keyup, keypress true, // bubbles true, // cancelable window, // view: should be window false, // ctrlKey false, // altKey false, // shiftKey false, // metaKey 40, // keyCode: unsigned long - the virtual key code, else 0 0, // charCode: unsigned long - the Unicode character associated with the depressed key, else 0 ); document.dispatchEvent(keyboardEvent);
我想模拟按Tab键……扩展Trevor的回答,我们可以看到像“tab”这样的特殊键确实会被按下,但我们看不到按“tab”会产生的实际结果……
尝试与调度这些事件的'activeElement'以及全局文档对象都-代码添加下面;
代码片段如下:
var element = document.getElementById("firstInput"); document.addEventListener("keydown", function(event) { console.log('we got key:', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); /* enter is pressed */ if (event.keyCode == 13) { console.log('enter pressed:', event); theKey = 'Tab'; attributes = { bubbles: true, key: theKey, keyCode: 9, charCode: 0, }; setTimeout(function() { /* event.keyCode = 13; event.target.value += 'b'; */ var e = new window.KeyboardEvent('focus', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.activeElement.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.activeElement.dispatchEvent(e); }, 4); setTimeout(function() { var e = new window.KeyboardEvent('focus', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keydown', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('beforeinput', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keypress', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('input', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('change', attributes); document.dispatchEvent(e); e = new window.KeyboardEvent('keyup', attributes); document.dispatchEvent(e); }, 100); } else if (event.keyCode != 0) { console.log('we got a non-enter press...: :', event.key, ' keyCode:', event.keyCode, ' charCode:', event.charCode); } }); <h2>convert each enter to a tab in JavaScript... check console for output</h2> <h3>we dispatchEvents on the activeElement... and the global element as well</h3> <input type='text' id='firstInput' /> <input type='text' id='secondInput' /> <button type="button" onclick="document.getElementById('demo').innerHTML = Date()"> Click me to display Date and Time.</button> <p id="demo"></p>
在某些情况下,按键事件不能提供所需的功能。从mozilla文档中我们可以看到该特性已被弃用:
不再推荐使用此特性。虽然一些浏览器可能仍然支持它,但它可能已经从相关的网络标准中删除了,可能正在被删除的过程中,或者可能只是为了兼容性的目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表,以指导您的决定。请注意,此功能可能在任何时候停止工作。
因此,由于按键事件是由两个随后触发的事件keydown和接下来的同一个按键的keyup组合而成的,只需一个接一个地生成事件:
element.dispatchEvent(new KeyboardEvent('keydown',{'key':'Shift'}));
element.dispatchEvent(new KeyboardEvent('keyup',{'key':'Shift'}));
在alex2k8的基础上,这里有一个修订版,可以在jQuery支持的所有浏览器中工作(问题是缺少jQuery.event的参数。触发器,在使用内部函数时很容易忘记它)。
// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
// Internally calls jQuery.event.trigger with arguments (Event, data, elem).
// That last argument, 'elem', is very important!
jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};
jQuery(function ($) {
// Bind event handler
$('body').keypress(function (e) {
alert(String.fromCharCode(e.which));
console.log(e);
});
// Simulate the key press
$('body').simulateKeyPress('x');
});
您甚至可以更进一步,让它不仅模拟事件,而且实际插入字符(如果它是一个输入元素),但是在尝试这样做时,有许多跨浏览器的问题。最好使用更精致的插件,如SendKeys。
让它工作的关键部分是认识到charCode, keyCode和这些都是不推荐的方法。因此,如果处理按键事件的代码使用这三个中的任何一个,那么它将收到一个伪答案(例如,默认值为0)。
只要使用非弃用的方法(如key)访问按键事件,就应该没问题。
为了完成,我添加了触发事件的基本Javascript代码:
const rightArrowKey = 39 const event = new KeyboardEvent('keydown',{'key':rightArrowKey}) document.dispatchEvent(事件)