Insert text in a textarea/text input at the cursor, when code is being executed in a Chrome Extension content script

送分小仙女□ 提交于 2019-12-06 14:19:43

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/4418958/insert-text-in-a-textarea-text-input-at-the-cursor-when-code-is-being-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!