制作油猴(Tampermonkey)插件其实并不复杂,它本质上是一个包含特定元数据的 JavaScript 脚本。
以下是一个示例:
// ==UserScript==
// @name 示例油猴插件
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 这是一个简单的油猴插件示例,用于演示基本功能
// @author 你的名字
// @match https://www.example.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
// 插件的主要功能代码
console.log('油猴插件已运行!');
// 修改页面标题
document.title = '【已被油猴插件修改】' + document.title;
// 修改页面背景色
document.body.style.backgroundColor = '#f0f8ff';
// 添加一个提示框
const alertDiv = document.createElement('div');
alertDiv.style.position = 'fixed';
alertDiv.style.top = '20px';
alertDiv.style.right = '20px';
alertDiv.style.padding = '10px 20px';
alertDiv.style.backgroundColor = '#4CAF50';
alertDiv.style.color = 'white';
alertDiv.style.borderRadius = '5px';
alertDiv.style.zIndex = '9999';
alertDiv.textContent = '油猴插件已生效!';
document.body.appendChild(alertDiv);
// 3秒后自动移除提示框
setTimeout(() => {
alertDiv.style.opacity = '0';
alertDiv.style.transition = 'opacity 0.5s';
setTimeout(() => alertDiv.remove(), 500);
}, 3000);
})();
油猴插件的基本结构解析
-
元数据块(Metadata Block):
这部分以// ==UserScript==
开始,// ==/UserScript==
结束,包含插件的基本信息:@name
:插件名称@namespace
:通常使用个人域名或固定值@version
:版本号@description
:插件描述@author
:作者名称@match
:指定插件生效的网址,支持通配符@grant
:声明需要的特殊权限,none
表示不需要额外权限
-
执行代码:
通常包裹在一个自执行匿名函数中,使用'use strict'
开启严格模式,避免变量污染。
如何安装和使用
- 安装 Tampermonkey 浏览器扩展
- 点击 Tampermonkey 图标,选择 "创建新脚本"
- 删除默认代码,粘贴上面的示例代码
- 按
Ctrl+S
保存 - 访问
https://www.example.com
即可看到效果
进阶开发方向
- 可以使用
@grant
申请更多权限,如GM_xmlhttpRequest
进行跨域请求 - 通过
@require
引入外部库,如 jQuery - 使用
GM_setValue
和GM_getValue
存储用户配置 - 针对特定网站开发功能,如自动填写表单、去除广告等