问题
My extension has a context menu with items. What I'd like it to do: is when I right-click an editable
html element (eg input or textarea) and then select and click on an item in my menu - some value defined by my extension gets entered into the input.
For now I have realised that with document.activeElement.value = myValue
.
With simple inputs it works alright.
Problems start when there is an input with custom onChange
event handling, eg a calendar or a phone input, or currency input - that transforms user-input in some way.
Since I am setting a value directly onto the element - the handling logic gets omitted, which causes all manner of problems.
Since javascript doesn't allow for KeySend-like features - what are my options here?
I have thought about testing tools like Puppeteer or Cypress - but they all seem not to be packageable into an extension. Puppeteer does have such an option, but it still requires a node instance running to connect to. And I would like my extension to be solely client-sided and distributed in Chrome webstore - so I cannot ask my users to run spin up a node server.
回答1:
There is a built-in DOM method document.execCommand.
(Disregard the bit about "designMode", it's irrelevant as execCommand works by default, at least its "insertText" command)
document.querySelector('some.selector').focus();
document.execCommand('insertText', false, 'new text')
It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput
, input
, and consequently change
if applicable) with isTrusted
field set to true, more info in the spec draft. As the spec says, there has been a lot of bugs and discrepancies in browser implementations of this API but generally insertText
command works across modern browsers without problems.
来源:https://stackoverflow.com/questions/57879322/chrome-extension-enter-data-into-a-custom-handled-input-field