是否可以在JavaScript中以编程方式模拟按键事件?
当前回答
在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。
其他回答
您所能做的就是通过触发键事件以编程方式触发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上下文中,此工具和键码映射将派上用场。
披露:答案是基于这里的答案。
由于在控制台上下文中易于使用,它曾经是单行的。但可能还是有用的。
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);
我想模拟按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>
只需使用CustomEvent
Node.prototype.fire=function(type,options){
var event=new CustomEvent(type);
for(var p in options){
event[p]=options[p];
}
this.dispatchEvent(event);
}
4 ex想模拟ctrl+z
window.addEventListener("keyup",function(ev){
if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
})
document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})
这对我来说是有效的,它确实为我的textaera模拟了一个按键。如果你想在整个页面中使用它,只需将KeySimulation()放在<body>上,就像这样<body onmousemove="KeySimulation()“>或如果不是onmousemove,那么onmouseover或onload也可以。
function KeySimulation() { var e = document.createEvent("KeyboardEvent"); if (e.initKeyboardEvent) { // Chrome, IE e.initKeyboardEvent("keyup", true, true, document.defaultView, "Enter", 0, "", false, ""); } else { // FireFox e.initKeyEvent("keyup", true, true, document.defaultView, false, false, false, false, 13, 0); } document.getElementById("MyTextArea").dispatchEvent(e); } <input type="button" onclick="KeySimulation();" value=" Key Simulation " /> <textarea id="MyTextArea" rows="15" cols="30"></textarea>