油猴脚本开发基础
1. 油猴脚本深度解析
1.1 什么是油猴脚本?
- 本质:基于JavaScript的浏览器扩展脚本
- 工作原理:在网页加载时注入自定义JS代码
- 核心能力:
- 修改DOM结构
- 拦截网络请求
- 操作浏览器API
- 存储本地数据
- 应用场景:
- 广告屏蔽
- 网页功能增强
- 自动化操作
- 数据提取与分析
- 界面个性化定制
1.2 浏览器支持矩阵
浏览器 | 推荐扩展 | 官方地址 |
---|---|---|
Chrome | Tampermonkey | 链接 |
Firefox | Greasemonkey/Tampermonkey | 链接 |
Edge | Tampermonkey | 链接 |
Safari | Userscripts | 链接 |
2. 专业开发环境搭建
2.1 编辑器配置(VS Code推荐)
- 打开油猴访问本地权限
- 接着在油猴设置
- 准备开发
注意// @require
链接到你的javascript脚本。 - vscode测试
console.log("this is a test");
- 开启脚本并验证
2.2 Tampermonkey 高级功能
- 脚本沙箱:独立执行环境避免冲突
- 脚本自动更新:通过
@updateURL
配置 - 资源加载:
@require
引入外部库 - 权限控制:
@grant
管理API访问 - 运行时机控制:
@run-at
指定注入时机
3. 脚本结构深度剖析
3.1 元数据块详解
// ==UserScript==
// @name 高级脚本示例
// @namespace https://your-domain.com
// @version 1.2.0
// @description 多功能网页增强工具
// @author 你的名字
// @icon https://example.com/icon.png
// @match *://*.taobao.com/*
// @exclude *://*.taobao.com/payment/*
// @require https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @connect api.example.com
// @run-at document-idle
// @noframes
// ==/UserScript==
3.2 元数据参数权威指南
参数 | 必需 | 描述 | 示例 | 注意事项 |
---|---|---|---|---|
@name | ✓ | 脚本名称 | @name 淘宝助手 | 显示在TM面板 |
@namespace | ✓ | 唯一命名空间 | @namespace https://github.com/yourname | 防止命名冲突 |
@version | ✓ | 语义化版本 | @version 1.0.3 | 主版本.次版本.修订号 |
@description | ✓ | 简短描述 | @description 自动领取优惠券 | <80字符 |
@match | ✓ | URL匹配规则 | @match *://*.jd.com/* | 支持通配符* |
@exclude | 排除URL | @exclude *://jd.com/checkout* | 优先级高于@match | |
@require | 外部库依赖 | @require https://code.jquery.com/jquery-3.6.0.min.js | 先于主脚本加载 | |
@grant | API权限声明 | @grant GM_notification | 未声明将无法使用 | |
@run-at | 注入时机 | @run-at document-start | 可选:document-start , document-end , document-idle (默认) | |
@noframes | 禁止iframe | @noframes | 防止在iframe中运行 | |
@connect | 跨域白名单 | @connect api.example.com | 配合GM_xmlhttpRequest使用 |
4. 脚本编写最佳实践
4.1 安全编码规范
(function() {'use strict'; // 启用严格模式// 错误处理封装function safeDOMOperation(selector, callback) {try {const element = document.querySelector(selector);if (element) callback(element);} catch (e) {console.error(`DOM操作失败: ${e.message}`, e);}}// 主逻辑封装function initScript() {// 1. 移除顶部广告safeDOMOperation('.ad-banner', el => el.remove());// 2. 添加功能按钮safeDOMOperation('.header', header => {const btn = document.createElement('button');btn.textContent = '一键优化';btn.addEventListener('click', optimizePage);header.prepend(btn);});}// 等待页面关键元素加载if (document.readyState === 'loading') {document.addEventListener('DOMContentLoaded', initScript);} else {initScript();}
})();
4.2 脚本生命周期管理
- 加载阶段:解析元数据 → 加载@require资源
- 注入阶段:根据
@run-at
选择注入时机 - 执行阶段:执行主函数
- 卸载阶段:监听页面卸载事件清理资源
// 资源清理示例
const resources = new Set();function addResource(element) {resources.add(element);return element;
}window.addEventListener('beforeunload', () => {resources.forEach(res => res.remove());
});
5. 调试大师课
5.1 调试工具链
工具 | 用途 | 快捷键 |
---|---|---|
Tampermonkey 内置调试器 | 查看脚本运行状态 | 点击TM图标→选择脚本 |
浏览器开发者工具 | 元素检查/网络分析 | F12 |
Console 日志 | 输出调试信息 | console.log() |
Debugger 语句 | 断点调试 | debugger; |
5.2 高级调试技巧
// 1. 带样式的日志输出
console.log('%c脚本状态', 'color: blue; font-weight: bold', {version: '1.0',page: location.href
});// 2. 性能监控
const startTime = performance.now();
// ...执行代码...
console.log(`执行耗时: ${performance.now() - startTime}ms`);// 3. 网络请求监控
const open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {this.addEventListener('load', function() {console.log('XHR请求:', arguments[1], this.response);});open.apply(this, arguments);
};
6. 学习资源推荐
-
官方文档:
- Tampermonkey 文档
- Greasy Fork 脚本规范
-
优质教程:
- 油猴脚本开发从入门到精通
- MDN Web Docs - DOM操作
-
实用工具:
- UserScript Generator - 元数据生成器
- Violentmonkey - 开源替代方案
-
脚本市场:
- Greasy Fork
- OpenUserJS
7. 常见问题解决方案
问题 | 原因 | 解决方案 |
---|---|---|
脚本未执行 | @match配置错误 | 使用*://*/* 测试,逐步缩小范围 |
DOM操作失效 | 元素动态加载 | 使用MutationObserver 或setInterval 检测 |
跨域请求失败 | 未声明@connect | 添加@grant GM_xmlhttpRequest 和@connect 域名 |
样式冲突 | 优先级不足 | 使用!important 或更具体的选择器 |
脚本更新延迟 | 缓存问题 | 在脚本URL后添加?v=版本号 |