我尝试通过contentScript文件发送命令,以删除用户插入的<input>字段中字符串的最后一个字符。

已经尝试了几种在网络上找到的方法,但是没有任何效果。

我最后一次尝试与TextEvent一样(如下面的代码),但没有成功。

contentScript.js-Reference

document.getElementById("inputTextId").value = "Some string inserted by user";
var textEvent = document.createEvent('TextEvent');
textEvent.initTextEvent('textInput', true, true, null, String.fromCharCode(13), 9, "en-US");
document.getElementById("inputTextId").dispatchEvent(textEvent);


真的有可能做到这一点吗?

最佳答案

您不能通过这样的关键事件来自动进行编辑:这根本是不可能的。如果要删除输入值的最后一个字符,只需通过获取/设置输入的value属性直接执行此操作:

input.value = input.value.slice(0, -1);


如果要更逼真的退格效果,则只需使用selectionStartselectionEnd

var value = input.value;                                                // get the value of the input
var start = input.selectionStart;                                       // get the start index of the selection of the input
var end = input.selectionEnd;                                           // get the end index of the selection of the input

if(start === end) {                                                     // if nothing is selected, i.e. start is the same as end which is the position of the carret
    if(start > 0) {                                                     // if the carret is not at position 0 (nothing to remove in this case)
        input.value = value.slice(0, start - 1) + value.slice(start);   // remove one character before the carret
        input.selectionStart = input.selectionEnd = start - 1;          // set the new carret position
    }
} else {                                                                // otherwise, if there is a selection
    input.value = value.slice(0, start) + value.slice(end);             // just remove the selection from the input. Don't remove any other characters
    input.selectionStart = input.selectionEnd = start;                  // set the new carret position
}

10-06 00:11