avril alejandro answer is good, this is a different approach to solve the problem
Logic is, when user clicks your context menu item, menu will disappear and focus is back right where you need it, on origin element from which right click started (also from any point in that element if user clicked somewhere in the middle of existing text)
All you need to do is simulate copy/paste action.
so, in background script:
- in your
onClicked
listener create textarea
- fill it with value you want to insert (date string in this example)
- focus it and select it
- use
document.execCommand('Copy')
to put taxarea
value into clipboard
- if click started from iframe, make sure you target only that frame, to avoid multiple script insertion and errors
- inject script into sender tab (you have all the info from
onClicked
listener)
- injected script will do only one thing, pasting what was is in the clipboard
document.execCommand('paste')
background.js
chrome.contextMenus.onClicked.addListener(function(info, tab) {
var tArea = document.createElement('textarea'), _frame = null, date = new Date();
document.body.appendChild(tArea);
tArea.value = date.toLocaleString();
tArea.focus();
tArea.select();
document.execCommand('copy');
if(info.frameId) _frame = info.frameId;
chrome.tabs.executeScript(tab.id, {frameId: _frame, matchAboutBlank: true, code:
"document.execCommand('paste');"
}, function() {
if (chrome.runtime.lastError) console.log(chrome.runtime.lastError);
document.body.removeChild(tArea);
});
});
in your manifest add "clipboardWrite", "clipboardRead", "activeTab"
permissions
I'm using this logic in my Opera notes extension.
I never saw anyone using this trick, and it's very simple, plus it will remove all the hassle with targeting the right element, selections, ranges, rich text editors ...etc