Insert text in a textarea/text input at the cursor, when code is being executed in a Chrome Extension content script
I am making a Chrome extension that places some stored, regularly used bits of text, into text inputs and text areas when a context menu item is chosen.
The way it's set up to work at the moment, there's a line in the content script which takes care of the insertion:
document.activeElement.value = "TEXT TO INSERT" + document.activeElement.value ;This puts the text at the start of whichever textbox/editable area is selected. It would be desirable to insert the text wherever the user i开发者_如何学Gos currently clicked in the textbox, rather than just at the start.
I have seen lots of examples for inputting text at the cursor/caret, but haven't been able to get them to work from a content script. As this doesn't need to be cross-browser compatible, what's the easiest way to make this text insert at the cursor?
Thanks for your help
The solution is using the code found at http://www.sitepoint.com/forums/showthread.php?t=709013
Changing the first couple of lines of that script so that they read
function insertAtCaret(text) {
var txtarea = document.activeElement;
The javascript then doesn't need the id of the selected element declared.
This goes in the content script, along with
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
insertAtCaret(request.text);
if (request.greeting == "hello")
sendResponse({farewell: "laters"});
else
sendResponse({farewell: "byebye"}); // snub them.
});
精彩评论