You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Window对象获取已创建Monaco编辑器的光标位置?

获取Monaco编辑器实例及光标位置(浏览器扩展场景)
  • 从DOM容器直接取实例
    Monaco编辑器的DOM容器会和实例绑定,你可以通过容器的内部属性拿到实例:
const container = document.querySelector(".monaco-editor");
// 注意__internal_instance是内部属性,版本更新可能变动
const editorInstance = container.__internal_instance?.editor;

if (editorInstance) {
  const cursorPos = editorInstance.getPosition();
  console.log(`光标位置:行${cursorPos.lineNumber},列${cursorPos.column}`);
}
  • 通过Model反向找编辑器
    你已经能拿到Model,可以利用它关联的编辑器集合定位目标实例:
const model = monaco.editor.getModels()[0];
// 部分版本支持getEditors(),先做兼容判断
const allEditors = typeof monaco.editor.getEditors === 'function' ? monaco.editor.getEditors() : [];
const targetEditor = allEditors.find(editor => editor.getModel() === model);

if (targetEditor) {
  const cursorPos = targetEditor.getPosition();
  console.log(`光标位置:行${cursorPos.lineNumber},列${cursorPos.column}`);
}

如果getEditors()不存在,试试Model的内部关联集合:

const attachedEditors = model._attachedEditors || [];
if (attachedEditors.length > 0) {
  const cursorPos = attachedEditors[0].getPosition();
  console.log(`光标位置:行${cursorPos.lineNumber},列${cursorPos.column}`);
}
  • 注意事项
    • 浏览器扩展脚本要运行在页面上下文,否则无法访问window.monaco和DOM内部属性。
    • 上面用到的内部属性(__internal_instance、_attachedEditors)没有官方API保障,Monaco版本升级后可能失效,优先用稳定方法。

内容的提问来源于stack exchange,提问作者Adam M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:12:03