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

时间:2015-03-15 23:33:32

标签: javascript google-chrome-extension ace-editor

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

enter image description here

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>

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

...    
"content_scripts": 
      [{
        "matches": ["*://*.github.com/*/edit/*"],
        "js":      ["ace.js", "content.js"]
      }],
...

这是用户提供的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
    ...
}

我收到此错误

Error in event handler for runtime.onMessage: TypeError: Cannot read property 'editor' of undefined

===编辑1 ====

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

感谢引导我使用该解决方案的用户, 这就是我的所作所为:

使用ace API,下载js文件:https://github.com/ajaxorg/ace-builds/blob/master/src/ace.js

manifest.json:

  "content_scripts": 
  [{
    "matches": ["*://*.github.com/*/edit/*"],
    "js":      ["ace.js", "jquery.js", "content.js"]
  }],

由于安全问题,我无法直接检索ace编辑器对象,因此我需要注入此脚本:

function InsertToAceEditor(message)
{
    var scriptContent = "document.querySelector('.ace_editor').env.editor.insert('" +  message+ " ')";
    var script = document.createElement('script');
    script.id = 'tmpScript';
    script.appendChild(document.createTextNode(scriptContent));
    document.body.appendChild(script);
    $("#tmpScript").remove();
}

正如用户所指出的,这里有解释:https://stackoverflow.com/a/24344154/1743328