使用javascript捕获网页上的键盘输入

时间:2018-08-12 08:56:09

标签: javascript firefox-webextensions

我想使用javascript控制网页的输入焦点。实际上,我正在开发一个webExtension来将内容脚本加载到网页上。该网页经过预先设计,可以自动收集键盘输入。但是,我希望我的脚本在某些情况下可以通过附在页面上的inputBox接收键盘输入。但是所有的键盘输入似乎都是页面的原始inputBox。这是我目前的草稿

//TODO: steal focus to myInputBox
//while keydown is shiftkey, steal and retain the focus on myInputBox
//subsequently collect keyboard inputs
document.addEventListener("keydown", function(e){
 if (e.shiftKey)    
 {
  e.preventDefault(); //prevent shiftkey from modifying the input, I guess. Still learning though
  document.getElementById("myInputBox").focus(); //focus myInputBox subsequently accepting keyboard input from now on...
 }
});

但是键盘输入仍然转到原始的inputBox

////////很好,我找到了解决方法。这是我的解决方法,可能会对其他人有所帮助

document.addEventListener("keyup",function(){

if (e.key == "A" || e.key == "a")
{
    var origInput = document.getElementById("origInputID");

    origInput.disabled = !origInput.disabled;//use "!" to toggle current 
                                            //state
    if (origInput.disabled === true)
    {
        document.getElementById("myInput").focus();
    }
}});

1 个答案:

答案 0 :(得分:0)

您的示例对我有用。我对其进行了更新,以便在换档降低时在替代框中键入内容,然后在换档升高时在原始框中键入内容。不确定是否是您想要的...

要在按住Shift键的同时获取未移动的字符,您可能必须跟踪Shift键的状态,然后打开键代码。我认为您无法阻止Shift键影响生成的字符。防止默认值不会导致生成不同的字符码,键码将保持不变。

字符代码-代表ASCII字符的数字

键码-一个数字,代表键盘上的实际键

let editMode = false

document.addEventListener("keydown", function(e) {
  if (e.shiftKey && !editMode) {
    //e.preventDefault();
    editMode = true
    document.getElementById("myInputBox").focus();
  }
})

document.getElementById("myInputBox").addEventListener("keyup", function(e) {
  if (editMode && !e.shiftKey) {
    //e.preventDefault();
    editMode = false
    document.getElementById("other").focus();
  }
})

document.getElementById("other").focus();
Start with focus here, then press and hold shift
<input id='other'></input>
<hr />
Target
<input id='myInputBox'></input>