document.execCommand api has been marked as
Obsolete. However, given the situation that new API is still under construction, so it’s still safe to use it for now and maybe for next few years.
Normally you just need to do something like
document.querySelector('input').value="text you want to set" to get the job done easily and quickly.
But life is not always so easy. Actually most of the time you need to do more in browser extension development. The input fileds always bond many events like
change, or even
active. If you just set the
And before that you will need to find out what events you need to trigger. It gonna take you some time.
document.execCoomand, you can do it easily.
The syntax is like this:
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)
There is a insertText you can use to set value.
Inserts the given plain text at the insertion point (deletes selection).
so to insert text in to a field, you just, focus the field -> select the field -> execute the command, like so:
const element = document.querySelector("#target") element.focus() element.select() document.execCommand("insertText", false, "text you want to set")
The best of this API is that, it imitates user input event, make it like human being activity, trigger all bond events on the filed.
This API is very powerful, there are a bunch of commands you can use to make you life easier.
You can read it’s doc on MDN to get more details: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand