【问题标题】:Insert text in a textarea/text input at the cursor, when code is being executed in a Chrome Extension content script在 Chrome 扩展内容脚本中执行代码时,在光标处的文本区域/文本输入中插入文本
【发布时间】:2010-12-11 21:07:41
【问题描述】:

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.

目前它的设置方式是,内容脚本中有一行负责插入:
document.activeElement.value = "要插入的文本" + document.activeElement.value ;

这会将文本放在所选文本框/可编辑区域的开头。最好将文本插入文本框中用户当前单击的任何位置,而不是仅仅在开始处。

我已经看到很多在光标/插入符号处输入文本的示例,但无法让它们从内容脚本中工作。由于这不需要跨浏览器兼容,那么让此文本插入光标处的最简单方法是什么?

感谢您的帮助

【问题讨论】:

  • 如果它用于 Chrome 扩展,为什么需要跨浏览器兼容?
  • 嗨 Mike,它不需要跨浏览器兼容 - 只适用于 Chrome。

标签: javascript textarea google-chrome-extension


【解决方案1】:

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

更改该脚本的前几行,以便它们阅读

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

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

这与内容脚本一起出现

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

【讨论】:

  • 您能否在答案中添加 manifest.js 和其他脚本作为工作示例?
猜你喜欢
  • 2011-03-19
  • 2010-10-30
  • 2011-07-09
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-20
相关资源
最近更新 更多