简体   繁体   English

Chrome 扩展程序如何在任何选定的文本字段中输入文本

[英]Chrome extension how to enter text in any selected text field

I am making a Chrome extension that generates nicknames when you press Ctrl+Shift+U, and it should automatically enter the generated name in the selected text field, if one is selected.我正在制作一个 Chrome 扩展程序,当您按 Ctrl+Shift+U 时它会生成昵称,如果选择了一个,它应该会自动在选定的文本字段中输入生成的名称。 My problem is that there are many types of text fields, the most basic being input.我的问题是有很多类型的文本字段,最基本的是输入。 This is currently my function that generates the nickname, which works for input fields and textarea fields, but for nothing else.这是我目前生成昵称的 function,它适用于输入字段和文本区域字段,但除此之外别无他用。

//Nickname gets generated here
//...

var inp = document.querySelectorAll("input");
var txt = document.querySelectorAll("textarea");
    
for (var i=0;i<inp.length;i++) {
    if (inp[i] == document.activeElement) {
        inp[i].value = nick;
    }
}
    
for (var i=0;i<txt.length;i++) {
    console.log(txt[i]);
    if (txt[i] == document.activeElement) {
        txt[i].innerHTML = nick;
    }
}

Basically, what I think I would need, is some kind of function that can act like the user is typing the name, without directly changing the value of a field.基本上,我认为我需要的是某种 function,它可以像用户输入名称一样工作,而无需直接更改字段的值。

Thanks to the answer of wOxxOm , with a bit of modification, I got it to work.感谢wOxxOm的回答,经过一些修改,我让它开始工作。 This is my final code:这是我的最终代码:

//Nickname gets generated here
//...

const keyboardEventInit = {bubbles:false, cancelable:false, composed:false, key:'', code:'', location:0};
const element = document.activeElement;

if (element) {

    element.dispatchEvent(new KeyboardEvent("keydown", keyboardEventInit));
    element.value = nick;
    element.dispatchEvent(new KeyboardEvent("keyup", keyboardEventInit));
    element.dispatchEvent(new Event('change', {bubbles: true}));

}

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

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