在Chrome扩展内容脚本中执行代码时,将文本插入到光标处的textarea /文本输入中 [英] Insert text in a textarea/text input at the cursor, when code is being executed in a Chrome Extension content script
问题描述
我在制作一个Chrome扩展程序,用于将一些经常使用的文本存储在文本输入和文本区域中。它的设置目前的工作方式,内容脚本中有一行负责插入:
document.activeElement.value =TEXT TO INSERT+ document.activeElement.value;
这会将文本置于选定文本框/可编辑区域的起始位置。无论用户当前在文本框中单击的位置插入文本,而不仅仅是在开始处插入文本。
我已经看到很多用于在文本框中输入文本的示例光标/插入符号,但无法使它们从内容脚本中工作。由于这不需要跨浏览器兼容,所以在光标处插入此文本最简单的方法是什么?
感谢您的帮助
解决方案使用 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.
});
这篇关于在Chrome扩展内容脚本中执行代码时,将文本插入到光标处的textarea /文本输入中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!