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

Chrome扩展无法访问LeetCode的Monaco Editor API求助

问题:Chrome扩展无法访问LeetCode的Monaco编辑器API

我开发的Chrome扩展想给LeetCode的Monaco代码编辑器注入文本,但在内容脚本里访问monaco对象一直失败,可是直接在浏览器控制台输入window.monaco却能正常获取到这个对象。

以下是我目前用的代码:

manifest.json

{
  "manifest_version": 3,
  "name": "LeetCode Template Injector",
  "version": "1.0",
  "description": "Insert algorithm templates into LeetCode editor.",
  "permissions": ["activeTab", "scripting"],
  "action": {},
  "content_scripts": [
    {
      "matches": ["https://leetcode.com/problems/*"],
      "js": ["content.js"]
    }
  ]
}

content.js

function checkMonacoEditor() {
  const interval = setInterval(() => {
    if (typeof monaco !== "undefined" && monaco.editor.getModels().length > 0) {
      console.log("monaco editor found");
    } else {
      console.log("Waiting for Monaco editor...");
    }
  }, 1000);
}

window.addEventListener("load", function () {
  checkMonacoEditor();
});

浏览器控制台截图:
控制台截图

解决方法

问题根源是Chrome扩展内容脚本的隔离机制:内容脚本运行在独立的JS上下文里,和页面自身的执行环境不共享变量,所以拿不到页面加载的monaco对象;而浏览器控制台是直接在页面主环境执行,自然能访问到。

方案1:注入脚本到页面主环境

修改content.js,通过创建<script>标签把访问Monaco的代码注入到页面主环境中:

function injectMonacoScript() {
  const script = document.createElement('script');
  script.textContent = `
    const checkInterval = setInterval(() => {
      if (typeof monaco !== "undefined" && monaco.editor.getModels().length > 0) {
        console.log("Monaco编辑器已找到");
        // 这里添加注入文本的逻辑,示例:
        const editor = monaco.editor.getEditors()[0];
        editor.setValue("// 你的算法模板代码\\n" + editor.getValue());
        clearInterval(checkInterval);
      } else {
        console.log("等待Monaco编辑器加载...");
      }
    }, 1000);
  `;
  document.head.appendChild(script);
  script.remove(); // 注入后清理标签
}

window.addEventListener('load', injectMonacoScript);

方案2:点击扩展图标触发注入(更灵活)

如果不想页面加载就自动执行,可以移除content_scripts配置,改用点击图标触发脚本注入:

  1. 更新manifest.json:
{
  "manifest_version": 3,
  "name": "LeetCode Template Injector",
  "version": "1.0",
  "description": "Insert algorithm templates into LeetCode editor.",
  "permissions": ["activeTab", "scripting"],
  "action": {}
}
  1. 添加background.js:
chrome.action.onClicked.addListener(async (tab) => {
  await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    func: () => {
      const checkInterval = setInterval(() => {
        if (typeof monaco !== "undefined" && monaco.editor.getModels().length > 0) {
          console.log("Monaco编辑器已找到");
          const editor = monaco.editor.getEditors()[0];
          editor.setValue("// 你的算法模板\\n" + editor.getValue());
          clearInterval(checkInterval);
        } else {
          console.log("等待Monaco编辑器加载...");
        }
      }, 1000);
    }
  });
});

内容的提问来源于stack exchange,提问作者Siddharth Saurav

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 06:50:07