我的扩展有一个包含项目的上下文菜单。我希望它做什么:当我右键单击可编辑的 HTML 元素(例如输入或文本区域),然后选择并单击菜单中的某个项目时 - 由我的扩展定义的某个值被输入到输入中。
现在我已经意识到:
document.activeElement.value = myValue
只需简单输入即可正常工作。
当存在带有自定义 onChange
事件处理的输入时,就会出现问题,例如日历或电话输入,或货币输入 - 以某种方式转换用户输入。
由于我直接在元素上设置值 - 处理逻辑被省略,这会导致各种问题。
由于 JavaScript 不允许类似 KeySend 的功能 - 我有什么选择?
我考虑过测试像 Puppeteer 或 Cypress 这样的工具 - 但它们似乎都不能打包到扩展中。 Puppeteer 确实有这样的选项,但它仍然需要运行一个节点实例才能连接。我希望我的扩展程序仅在客户端并在 Chrome 网上应用店中分发 - 所以我不能要求我的用户启动节点服务器。
最佳答案
有一个内置的 DOM 方法 document.execCommand .
如果需要扩展,请在 content script 中使用此代码.
// some.selector may be `input` or `[contenteditable]` for richly formatted inputs
const el = document.querySelector('some.selector');
el.focus();
document.execCommand('insertText', false, 'new text');
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
它模仿物理用户输入到当前聚焦的 DOM 元素中,因此将触发所有必要的事件(例如 beforeinput
、input
) isTrusted
字段设置为 true。在某些页面上,应另外调度 change
事件,如上所示。
您可能想要选择当前文本以完全替换它而不是附加:
replaceValue('some.selector', 'new text');
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}
请注意,尽管 execCommand 在 2020 年被标记为过时,但它在可预见的 future 仍将发挥作用,因为新的编辑 API 规范尚未完成,并且要了解此类事物通常移动的速度可能还需要 5-20 年。
关于javascript - 如何在自定义处理的输入字段中输入数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57879322/