浏览器插件制作-优化Github显示

200 阅读2分钟

一、准备开发环境

  1. 创建项目文件夹 github-enhancer
  2. 安装VS Code或其他编辑器
  3. 确保使用最新版Edge浏览器(需支持Manifest V3)

二、创建基础文件结构

github-enhancer/
├── manifest.json        # 插件配置文件
├── content.css         # 样式优化文件
├── content.js          # 交互逻辑文件
└── icons/               # 插件图标
    ├── icon48.png
    └── icon128.png

三、编写核心文件(代码示例)

1. manifest.json 配置

{
  "manifest_version": 3,
  "name": "GitHub Enhancer",
  "version": "1.0",
  "description": "优化GitHub代码显示与界面布局",
  "icons": {
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "content_scripts": [{
    "matches": ["*://github.com/*"],
    "css": ["content.css"],
    "js": ["content.js"]
  }],
  "permissions": ["storage"],
  "host_permissions": ["*://github.com/*"]
}

2. content.css 样式优化

/* 增强代码块显示 */
.blob-code-inner {
  font-family: "Fira Code", monospace !important;
  font-size: 14px !important;
  line-height: 1.8 !important;
}

/* 暗色主题优化 */
[data-color-mode*="dark"] {
  --color-canvas-default: #1a1a1a !important;
  --color-border-default: #404040 !important;
}

/* 文件树导航栏固定宽度 */
.react-directory-truncate {
  max-width: 300px !important;
}

3. content.js 交互逻辑

// 自动展开差异代码块
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.js-file-header').forEach(header => {
    if(header.querySelector('.diffstat')) {
      header.closest('.file').querySelector('.js-details-target').click();
    }
  });

  // 为代码行添加点击复制功能
  document.querySelectorAll('.blob-code').forEach(line => {
    line.style.cursor = 'pointer';
    line.onclick = () => {
      navigator.clipboard.writeText(line.innerText);
      line.style.background = 'rgba(100, 255, 100, 0.1)';
      setTimeout(() => line.style.background = '', 1000);
    }
  });
});

四、测试与调试步骤

  1. 打开Edge浏览器访问 edge://extensions
  2. 启用 开发者模式 开关
  3. 点击 加载解压缩的扩展 选择项目文件夹
  4. 访问任意GitHub仓库(如https://github.com/microsoft/vscode

五、高级功能扩展建议

  1. 在manifest中添加 options_page 实现用户配置界面
  2. 使用Storage API保存用户主题偏好
  3. 通过MutationObserver监听动态加载的内容
  4. 添加快捷键支持(需注册commands)
// 示例:动态内容处理
const observer = new MutationObserver(mutations => {
  mutations.forEach(mut => {
    if(mut.addedNodes.length) {
      applyEnhancements(mut.target);
    }
  });
});

observer.observe(document.body, {
  childList: true,
  subtree: true
});

六、打包与发布

  1. 在Edge开发者中心注册账号
  2. 通过 npm install -g @microsoft/edge-dev-tools-cli 安装打包工具
  3. 执行 edge-extensions pack 生成.crx文件
  4. 提交至Microsoft Edge Add-ons商店