且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Chrome扩展内容脚本中执行代码时,将文本插入到光标处的textarea /文本输入中

更新时间:2023-08-17 23:46:10

解决方案使用 http://www.sitepoint.com/forums/showthread.php?t=709013



更改第一个这个脚本的几行代码,以便他们阅读

  function insertAtCaret(text){
var txtarea = document.activeElement ;

然后,javascript不需要声明所选元素的id。



这个内容脚本和

  chrome.extension.onRequest.addListener( 
函数(request,sender,sendResponse){
insertAtCaret(request.text);
if(request.greeting ==hello)
sendResponse({farewell:laters });
else
sendResponse({farewell:byebye}); // snub them。
});


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 is 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.    
});