All major browsers now support the document.activeElement property, which helps identify the currently focused field in a window where the cursor is located. To insert text at the current cursor position, you can use the following function:
// Script by: http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
// Enhanced for cross-browser compatibility
function insertAtCursor(targetField, textToInsert) {
var doc = targetField.ownerDocument;
// For Internet Explorer
if (doc.selection) {
targetField.focus();
sel = doc.selection.createRange();
sel.text = textToInsert;
}
// For Firefox and other browsers
else if (targetField.selectionStart || targetField.selectionStart == '0') {
var startPos = targetField.selectionStart;
var endPos = targetField.selectionEnd;
targetField.value = targetField.value.substring(0, startPos) +
textToInsert + targetField.value.substring(endPos, targetField.value.length);
}
// Fallback method to append text at the end
else {
targetField.value += textToInsert;
}
}
Therefore, in your popup, when handling button clicks, you should invoke the following function:
// A fictional but descriptive function name
function insertTextIntoFocusedTextFieldInOpener(textToAdd) {
var activeField = window.opener.document.activeElement;
if (activeField.tagName == "TEXTAREA" || (activeField.tagName == "INPUT" && activeField.type == "text")) {
insertAtCursor(activeField, textToAdd);
}
}