简体   繁体   English

在Firefox插件中模拟按键

[英]Simulate a Keystroke in Firefox addon

I want to be able to simulate a keystroke from my firefox-addon and at the moment I'm not being able to do that. 我希望能够模拟我的firefox插件的击键,但目前无法执行此操作。

I found this post Why simulation of Left Arrow + Shift keys doesnt work in Firefox? 我发现了这篇文章, 为什么在Firefox中无法模拟向左箭头键和Shift键? and my code is almost the same, but it only does the focus part, not the dispatchEvent. 和我的代码几乎相同,但是它只做焦点部分,而不是dispatchEvent。 Any idea why this could be happening? 知道为什么会这样吗?

Here is the code: 这是代码:

objTag.focus();
var e = document.createEvent('KeyboardEvent');
e.initKeyEvent('keydown', true, true, window, false, false, false, false, 35, 0);
objTag.dispatchEvent(e);

Your code is correct but the <textarea> element reacts to keypress events, not keydown . 您的代码正确,但是<textarea>元素对keypress事件做出反应,而不是keydown

Anyway, why so complicated? 无论如何,为什么这么复杂? You can just set input.value and then use input.setSelectionRange() method to move the cursor appropriately. 您可以只设置input.value ,然后使用input.setSelectionRange()方法适当地移动光标。 If you want to add something to the end of the current line you would do it like this: 如果要在当前行的末尾添加一些内容,可以这样:

var position = objTag.selectionStart;
var lineEnd = objTag.value.indexOf("\n", position);
if (lineEnd < 0) // No more line breaks
  lineEnd = objTag.value.length;

var textToAdd = "foo";
objTag.value = objTag.value.substr(0, lineEnd) + textToAdd + objTag.value.substr(lineEnd);
objTag.setSelectionRange(lineEnd + textToAdd.length, lineEnd + textToAdd.length);
objTag.focus();

Adding to the end of the text is even simpler: 在文本末尾添加内容更简单:

var textToAdd = "foo";
objTag.value += textToAdd;
objTag.setSelectionRange(objTag.value.length, objTag.value.length);
objTag.focus();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM