想让网页按你的想法运行?油猴(tampermonkey)脚本就是你的工具。通过编写自定义脚本,你可以自动执行操作、修改页面内容、屏蔽广告,甚至增强网站功能。下面是一套清晰的油猴脚本创建与调试流程,适合新手快速上手。
在开始编写前,先确保你已安装油猴扩展:
删除示例代码中的内容,准备从头写一个干净的脚本。

油猴脚本由两部分组成:顶部的元数据块和下方的JavaScript代码。
// ==UserScript==
// @name 我的第一个脚本
// @namespace http://tampermonkey.net/
// @version 1.0
// @description 尝试修改百度首页
// @author You
// @match https://www.baidu.com/*
// @grant none
// ==/UserScript==
关键字段说明:
alert,可设为 GM_notification
元数据结束后,写入JavaScript代码:
document.addEventListener('DOMContentLoaded', function() {
document.title = '已被脚本修改';
});保存后刷新目标页面,查看是否生效。
以下是一些常用场景的代码片段,可直接参考使用:
自动点击按钮
// 等待元素出现后再点击
function autoClick(selector) {
const btn = document.querySelector(selector);
if (btn) btn.click();
}
autoClick('#submit-btn');修改页面文字
const el = document.querySelector('h1');
if (el) el.textContent = '新标题:脚本已生效';注入CSS样式
const style = document.createElement('style');
style.textContent = `
body { background: #f0f8ff !important; }
.ad-banner { display: none !important; }
`;
document.head.appendChild(style);监听页面变化(如SPA页面)
const observer = new MutationObserver(() => {
console.log('页面结构更新');
// 在这里执行你的逻辑
});
observer.observe(document.body, { childList: true, subtree: true });脚本不生效?别急,按步骤排查:
console.log('测试') 确认是否执行建议开发阶段设置:
alert() 或 console.log() 输出调试信息基本上就这些。掌握结构、理解执行时机、善用调试工具,就能写出稳定可靠的油猴脚本。不复杂但容易忽略细节,多练几次就熟练了。
以上就是油猴脚本创建教程 油猴自定义脚本编写与调试流程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号