简体   繁体   English

从Chrome扩展程序触发本机键盘事件

[英]Trigger native keyboard events from a Chrome extension

Facebook have textarea's where they expand/shrink to the size of the text inside of it. Facebook具有textarea,可以在其中将文本扩展/缩小到其中的文本大小。 In my Chrome extension I change the text inside a textarea to be over several lines. 在我的Chrome扩展程序中,我将文本区域内的文本更改为多行。 However, the textareas expand/shrink method only works on keyboard events, so I have to trigger one. 但是,textareas扩展/收缩方法仅适用于键盘事件,因此我必须触发一个事件。

var event = document.createEvent('KeyboardEvent');

event.initEvent('keyup', true, true, window, false, false, false, false, 38, 38);
this.dispatchEvent(event); // this is the textarea

(It does this for all of keyup, keydown, keypress) (此操作适用于所有按键,按键按下,按键操作)

But this doesn't work. 但这是行不通的。 Now, I know a bit of why it doesn't work, but not how to solve it. 现在,我知道为什么它不起作用了,但是不知道如何解决它。 I have attached a handler to the element to see what is going on: 我已将处理程序附加到该元素,以查看发生了什么:

$('[role=dialog] .MessagingComposerForm textarea').on('keyup', function(e) {
    console.log(e);
});

When the Chrome extension triggers its keyup event, the object which I can see in my console is a normal Event object, except for two things: keyCode=0 and view=null. 当Chrome扩展程序触发其keyup事件时,我可以在控制台中看到的对象是普通的Event对象,除了两件事:keyCode = 0和view = null。

When I trigger the keyup event by hitting a key on my keyboard I can see that keyCode=38 and view=Window. 当我通过敲击键盘上的一个键来触发keyup事件时,我可以看到keyCode = 38和view = Window。

Does anyone have an idea on how to do this? 有谁知道如何做到这一点?

ADDED: 添加:

I discovered something. 我发现了一些东西。 If I console.log the event before it is dispatched it still doesn't contain the correct information. 如果我在分派事件之前console.log事件,它仍然不包含正确的信息。 Here: 这里:

var event = document.createEvent('KeyboardEvent');

event.initKeyboardEvent('keydown', true, true, window, false, false, false, false, 65, 65);
event.keyCode = 65;
event.which = 65;
event.charCode = 65;

console.log(event);

this.dispatchEvent(event); // this is the textarea

outpus this object: 胜过这个对象:

KeyboardEvent: {
    ...
    charCode: 0,
    keyCode: 0,
    view: Window,
    which: 0
}

This is a bug in WebKit: https://bugs.webkit.org/show_bug.cgi?id=16735 这是WebKit中的错误: https ://bugs.webkit.org/show_bug.cgi ? id =16735

30char 30个字符

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

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