有一个内置的DOM方法document.execCommand。 如果是扩展名,请在内容脚本中使用此代码。
document.querySelector('some.selector').focus();
document.execCommand('insertText', false, 'new text')
为当前关注的DOM元素,因此将在字段设置为true的情况下触发所有必需的事件(如beforeinput
,,input
因此,change
如果适用)isTrusted
。
您可能希望选择当前文本以完全替换它,而不是附加:
replaceValue('some.selector', 'new text');
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
document.execCommand('insertText', false, value);
}
return el;
}
请注意,execCommand在2020年被标记为已过时,但是它将在可预见的将来工作,因为新的编辑API规范尚未完成,并且知道此类操作通常需要多长时间才能完成。