在github ace编辑器上的插入位置

aze*_*r89 2 javascript google-chrome-extension ace-editor

我正在开发一个chrome扩展,我可以在github web编辑器中插入文本.插入的文本应该在插入符号位置,我无法弄清楚如何获取它.

在此输入图像描述

github编辑器是一个ace编辑器,它有以下HTML代码:

<div class="commit-create">
<textarea id="blob_contents"
      class="file-editor-textarea js-blob-contents js-code-textarea"
      rows="35" name="value"
      data-filename="README.md"
      data-language="Markdown"
      data-ace-mode="markdown"
      data-allow-unchanged=""
      data-test-id="blob-file-editor"
      placeholder="Enter file contents here"
      spellcheck="false"
      autofocus>
Line 1
Line 2
Line 3
Line 4
</textarea>
</div>
Run Code Online (Sandbox Code Playgroud)

在我的manifest.json中,我包含了ace.js(从这里获得,我希望它是正确的.js文件)

...    
"content_scripts": 
      [{
        "matches": ["*://*.github.com/*/edit/*"],
        "js":      ["ace.js", "content.js"]
      }],
...
Run Code Online (Sandbox Code Playgroud)

这是用户提供的javascript代码:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) 
{
    ...
    var editor = document.querySelector(".ace_editor").env.editor;
    var cursor = editor.selection.getCursor() // returns object like {row:1 , column: 4}
    editor.insert("text") // insert string at cursor
    ...
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

Error in event handler for runtime.onMessage: TypeError: Cannot read property 'editor' of undefined
Run Code Online (Sandbox Code Playgroud)

===编辑1 ====

感谢用户,我做了一点进步.该代码适用于chrome控制台,但它不适用于content.js,它可能是一个安全问题,我不明白为什么.

a u*_*ser 5

你需要使用ace api

var editor = document.querySelector(".ace_editor").env.editor;
var cursor = editor.selection.getCursor() // returns object like {row:1 , column: 4}
editor.insert("text") // insert string at cursor
Run Code Online (Sandbox Code Playgroud)