Subject:
I am creating a Google Chrome extension that interacts with web pages via a content script and an event page.
I have context menu options that appear if a user clicks on an element that is categorized as editable by the chrome.contextMenus API.
The options act like shortcuts for commonly entered text. When the user clicks an option, some text is placed inside the element at the position of the cursor. If the user has text highlighted, it is deleted.
Problem:
Not all editable elements can be modified the same way.
If the element is a simple textarea the desired result can be achieved by implementing this solution:
However, I can not assume that I am interacting with a normal textarea.
Possible nuances include:
The text area being hidden inside an
Iframe, which complicates the process of finding the element to interact with (document.activeElementmay return theIframe, rather than the element that actually contains the text).The
<textarea>not being a<textarea>/<input>at all, but rather acontentEditable <div>. The.valueapproach will not work in this case.
So I am searching for a flexible way to do this that can handle all edge cases elegantly.
Some solutions I have tried:
- option 1 :
I originally planned on storing the value in the system clipboard. Then, I could conceivably just usedocument.execCommand('paste')to modify the element. However, after trying it, this approach seems to have the same drawbacks as my initial approach. (See this question)
Additionally, this approach would delete whatever was in the clipboard before the operation. This is undesirable and any solution that utilizes this approach must provide a work around. - option 2 :
Another option that I have considered is dispatching keyboard events for each character in the string. However, with this solution, you still run into theIframeproblem and it doesn't allow you do use special Unicode characters. ┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻