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.
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.activeElement
may return the Iframe
, rather than the element that actually contains the text).
The <textarea>
not being a <textarea>
/<input>
at all, but rather a contentEditable <div>
. The .value
approach will not work in this case.
So I am searching for a flexible way to do this that can handle all edge cases elegantly.
document.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) Iframe
problem and it doesn't allow you do use special Unicode characters. ┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻Your problem consists of two subproblems:
There are several APIs that help with identifying the frame (use a combination of them, choose whichever combination fits best in your situation):
contextMenus.onClicked
event provides the tab's ID (tab.id
) as a property in an instance of tabs.Tab and the frame's URL (frameUrl
) in a separate object.chrome.tabs.executeScript
method can directly run a script in a frame.frameUrl
(or use a combination of the next methods).chrome.runtime.onMessage
listener, use chrome.tabs.sendMessage
to send a message to a specific frame identified by frameId
(since Chrome 41).chrome.webNavigation.getAllFrames
method to get a list of all frames in a tab for a given tabId
, then get the frameId
of the target frame by filtering the list of frames by a known frameUrl
.contextMenus.onClicked
will get the frameId
).Okay, assuming that you have the correct frame, you can simply use document.activeElement
to get the target element, because input elements get focused upon click.
If the target element is a <textarea>
or <input>
, then you can simply use
// Assume: elem is an input or textarea element.
var YOURSTRING = 'whatever';
var start = elem.selectionStart;
var end = elem.selectionEnd;
elem.value = elem.value.slice(0, start) + YOURSTRING + elem.value.substr(end);
// Set cursor after selected text
elem.selectionStart = start + YOURSTRING.length;
elem.selectionEnd = elem.selectionStart;
Otherwise, you need to know whether there is a content editable element, and if so, remove any selection if existent, and finally put your desired text over there.
var elem = document.activeElement;
if (elem && elem.isContentEditable) {
// YOURSTRING as defined before
var newNode = document.createTextNode(YOURSTRING);
var sel = window.getSelection();
// Remove previous selection, if any.
sel.deleteFromDocument();
// If there is no range in the selection, add a new one, with the
// caret set to the end of the input element to avoid the next error:
//"Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index."
if (sel.rangeCount === 0) {
sel.addRange(document.createRange());
sel.getRangeAt(0).collapse(elem, 1);
}
// Insert new text
var range = sel.getRangeAt(0);
range.insertNode(newNode);
// Now, set the cursor to the end of your text node
sel.collapse(newNode, 1);
}
Relevant documentation for the web platform APIs used in the last example:
Selection
Selection.deleteFromDocument()
Selection.collapse
Range
Range.insertNode
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With