技术人员的日常积累其中的一部分就是总结不同的使用工具。现在各种软件都提供网站形式,在网站场景里,Javascript 是统治语言。TamperMonkey 提供了一种在网站上运行自己脚本的一种方式,应该成为我们工具箱里的一种常用工具。
Tamper Monkey 是一个浏览器插件,可以使用在 Tamper 首页 https://www.tampermonkey.net/ 跳转到安装界面。
语法文档: https://www.tampermonkey.net/documentation.php
新建脚本模版
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @icon https://www.google.com/s2/favicons?sz=64&domain=tampermonkey.net
// @match http*://*/*
// @connect *
// @require https://code.jquery.com/jquery-2.1.4.min.js
// @run-at document-idle
// @grant unsafeWindow
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
// Your code here...
})();
@name, @namespace, @version, @description, @author, @icon 提供脚本的基本信息。
@match 规定了脚本在什么网站上运行,http*://*/*
表明运行在所有的网站上,*
可用作通配符。 @match 的网站格式需要符合<url-pattern>
的格式
<url-pattern> := <scheme>://<host><path>
<scheme> := '*' | 'http' | 'https' | 'file' | 'ftp' | 'urn'
<host> := '*' | '*.' <any char except '/' and '*'>+
<path> := '/' <any chars>
Tamper Monkey 支持 Ajax 调用函数 GM_xmlhttpRequest,@connect 指定了 ajax 可以调用的网址,* 表示可以调用任何网站,但会请求用户的确认,在不确定调用的网站是比较有用。 connect 规则:
加载脚本的依赖,像 jQuery 是比较常用的。
定义脚本的运行时机,支持 document-start
, document-body
, document-end
, document-idle
(default), context-menu
@grant 用于给 脚本添加一下GM_*
函数, unsafeWindow
对象权限。 unsafeWindow
是当前页面的 JS window 对象,可以引用到所有的全局变量。 GM 函数列表
函数名 | 功能 |
---|---|
GM_addStyle(css) | 加载 css |
GM_setValue(name, value) | 保存一个值 |
GM_getValue(name, defaultValue) | 获取key |
GM_deleteValue(name) | 删除一个值 |
GM_listValues() | 列出所有的 keys |
GM_log(message) | 打印日志 |
GM_openInTab(url, options) | 打开一个新tab |
GM_xmlhttpRequest(details) | ajax 调用 |
GM_setClipboard(data, info) | 保存data到剪贴板上,info 格式 "{ type: 'text', mimetype: 'text/plain'}" |
options 参数
Returns an object with the following property:
基本模版:
GM_xmlhttpRequest({
method: "GET",
url: "https://example.com",
timeout: 5000,
ontimeout: () => reject(' timeout'),
onload: function (response) {
if (response.status === 200) {
// do sth
resolve(response);
}
reject("Error occurred while retrieving data");
},
onerror: function (response) {
reject("Error occurred while retrieving data");
}
});
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有