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 a
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):
tab.id
) as a property in an instance of tabs.Tab and the frame's URL (frameUrl) in a separate object.frameUrl
(or use a combination of the next methods).frameId
(since Chrome 41).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: