Theme:
I am creating a Google Chrome extension that interacts with web pages through script content and an event page.
I have context menu options that appear if a user clicks on an item with an editable category using the chrome.contextMenus API ,
Options act as shortcuts for commonly entered text. When the user presses a parameter, some text is placed inside the element at the cursor position. If the user selects the text, it will be deleted.
Problem:
Not all editable items can be changed equally.
If the element is simple textarea , the desired result can be achieved by implementing this solution:
However, I cannot assume that I am interacting with regular textarea .
Possible nuances:
The text area hidden inside the Iframe , which complicates the process of finding an element to interact with ( document.activeElement can return an Iframe , rather than an element that actually contains text).
<textarea> not <textarea> / <input> at all, but rather a contentEditable <div> . In this case, the .value approach will not work.
So, I am looking for a flexible way to do this to elegantly handle all extreme cases.
Some solutions I tried:
- option 1:
I originally planned to save the value to the system clipboard. Then I could just use document.execCommand('paste') to modify the element. However, after trying this, this approach seems to have the same drawbacks as my original approach. (See this question )
In addition, this approach will delete everything that was on the clipboard before the operation. This is undesirable, and any solution using this approach should work.
- option 2:
Another option I examined is to send keyboard events for each character in a string. However, with this solution, you still encounter an Iframe problem, and this does not allow you to use special Unicode characters. ┻━┻ (ヽ (`D ') ノ (┻━┻
Lukep source share