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

Chrome扩展如何检测浏览器开发者模式是否已开启?

检测Chrome开发者模式是否开启的方法

Chrome并没有提供官方公开的API直接检测浏览器的开发者模式状态,但可以通过几种间接方式实现你的需求,覆盖未打包和打包后在开发者模式下测试的场景:

方案一:结合安装类型与目录访问检测

这种方法可以覆盖两种常见的开发者场景:直接加载未打包的扩展,以及将打包后的CRX解压后通过开发者模式加载。

let debugShow = false;

async function initDebug() {
  // 先检测扩展的安装类型
  const selfInfo = await chrome.management.getSelf();
  if (selfInfo.installType === "development") {
    debugShow = true;
  } else {
    // 尝试访问扩展目录,仅开发者模式下加载的解压扩展可成功
    try {
      await chrome.runtime.getPackageDirectoryEntry();
      debugShow = true;
    } catch (e) {
      debugShow = false;
    }
  }

  // 初始化你的调试代理
  window.debug = new Proxy({show: debugShow, void: () => {}}, {
    get(target, prop) {
      return target.show ? console[prop].bind(console) : target.void;
    }
  });
}

// 初始化
initDebug();

方案二:使用Chrome内部API(非官方,需注意兼容性)

Chrome提供了内部的chrome.developerPrivate API可以直接获取开发者模式的偏好设置,但这个API属于非公开接口,可能在后续版本中发生变化,且需要额外权限:

  1. 首先在manifest.json中添加权限:
"permissions": ["developerPrivate"]
  1. 然后编写检测代码:
let debugShow = false;

async function initDebug() {
  try {
    // 获取开发者模式偏好
    const prefs = await chrome.developerPrivate.getPreferences();
    // 不同Chrome版本可能使用不同字段,优先检查extensionsDeveloperMode
    debugShow = prefs.extensionsDeveloperMode ?? prefs.devToolsEnabled;
  } catch (e) {
    // API不可用时,回退到安装类型检测
    const selfInfo = await chrome.management.getSelf();
    debugShow = selfInfo.installType === "development";
  }

  window.debug = new Proxy({show: debugShow, void: () => {}}, {
    get(target, prop) {
      return target.show ? console[prop].bind(console) : target.void;
    }
  });
}

initDebug();

补充建议:手动调试开关

如果依赖开发者模式检测不可靠,你可以在扩展的弹出页或选项页中添加一个手动调试开关,让用户主动开启/关闭调试输出,这种方式更稳定,不受浏览器环境限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:48:46