是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
我想模拟按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>
其他回答
您可以创建和分派键盘事件,它们将触发相应的已注册事件处理程序,但是,如果分派到input元素,则不会产生任何文本。
要完全模拟文本输入,您需要生成一系列键盘事件,并显式地设置input元素的文本。事件的顺序取决于模拟文本输入的彻底程度。
最简单的形式是:
$('input').val('123');
$('input').change();
由于在控制台上下文中易于使用,它曾经是单行的。但可能还是有用的。
Var pressthiskey = "q"/* <——q为例*/; var e = new事件("keydown"); E.key =按下这个键; e.keyCode = e.key.charCodeAt(0); e.which = e.keyCode; e.altKey = false; e.ctrlKey = true; e.shiftKey = false; e.metaKey = false; E.bubbles = true; document.dispatchEvent (e);
您所能做的就是通过触发键事件以编程方式触发keyevent侦听器。从沙盒安全的角度来看,允许这样做是有意义的。使用此功能,您可以应用典型的观察者模式。您可以将此方法称为“模拟”。
下面是如何在W3C DOM标准和jQuery中实现这一点的示例:
function triggerClick() {
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var cb = document.querySelector('input[type=submit][name=btnK]');
var canceled = !cb.dispatchEvent(event);
if (canceled) {
// preventDefault was called and the event cancelled
} else {
// insert your event-logic here...
}
}
此示例改编自:https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
jQuery:
jQuery('input[type=submit][name=btnK]')
.trigger({
type: 'keypress',
which: character.charCodeAt(0 /*the key to trigger*/)
});
但是到目前为止,还没有[DOM]方法来触发离开浏览器沙箱的键事件。所有主要的浏览器供应商都将遵循这一安全概念。
至于Adobe Flash等基于NPAPI的插件,允许绕过沙盒:这些插件正在逐步淘汰;Firefox。
详细解释:
出于安全原因(正如Pekka已经指出的),您不能也不应该这样做。在两者之间总是需要用户交互。此外,想象一下浏览器供应商被用户起诉的可能性,因为各种编程键盘事件将导致欺骗攻击。
有关替代方案和更多细节,请参阅这篇文章。总是有基于flash的复制粘贴。这里有一个很好的例子。同时,它也证明了为什么网络正在远离插件供应商。
在选择加入CORS策略以编程方式访问远程内容的情况下,也应用了类似的安全思想。
答案是: 在正常情况下,在沙箱浏览器环境中无法以编程方式触发输入键。
底线:我并不是说在未来,在特殊的浏览器模式和/或游戏最终目标的特权下,这是不可能的,或类似的用户体验。然而,在进入这些模式之前,用户将被询问权限和风险,类似于全屏API模型。
有用:在KeyCodes上下文中,此工具和键码映射将派上用场。
披露:答案是基于这里的答案。
让它工作的关键部分是认识到charCode, keyCode和这些都是不推荐的方法。因此,如果处理按键事件的代码使用这三个中的任何一个,那么它将收到一个伪答案(例如,默认值为0)。
只要使用非弃用的方法(如key)访问按键事件,就应该没问题。
为了完成,我添加了触发事件的基本Javascript代码:
const rightArrowKey = 39 const event = new KeyboardEvent('keydown',{'key':rightArrowKey}) document.dispatchEvent(事件)
这种方法支持跨浏览器更改键代码的值。 源
var $textBox = $("#myTextBox");
var press = jQuery.Event("keypress");
press.altGraphKey = false;
press.altKey = false;
press.bubbles = true;
press.cancelBubble = false;
press.cancelable = true;
press.charCode = 13;
press.clipboardData = undefined;
press.ctrlKey = false;
press.currentTarget = $textBox[0];
press.defaultPrevented = false;
press.detail = 0;
press.eventPhase = 2;
press.keyCode = 13;
press.keyIdentifier = "";
press.keyLocation = 0;
press.layerX = 0;
press.layerY = 0;
press.metaKey = false;
press.pageX = 0;
press.pageY = 0;
press.returnValue = true;
press.shiftKey = false;
press.srcElement = $textBox[0];
press.target = $textBox[0];
press.type = "keypress";
press.view = Window;
press.which = 13;
$textBox.trigger(press);