Tampermonkey 语法
require 引入文件
- 引入后相当于在同一个文件内,可直接调用引入文件的函数。
GM_xmlhttpRequest Promise 写法
function getData(url, type = "document", usermethod = "GET") {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: usermethod,
url: url,
responseType: type,
onload: function (response) {
if (response.status == 200) {
resolve(response.response);
} else {
console.log("请求错误:" + response.status);
reject(response.status);
}
},
onerror: function (error) {
console.log("网络错误");
reject(error);
}
});
});
}
function postData(url, postData, type = "document", usermethod = "POST") {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: usermethod,
url: url,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
data: postData,
responseType: type,
onload: function (response) {
if (response.status == 200) {
resolve(response.response);
} else {
console.log("请求错误:" + response.status);
reject(response.status);
}
},
onerror: function (error) {
console.log("网络错误");
reject(error);
}
});
});
}
脚本执行顺序
console.log(0);
(function () {
'use strict';
console.log(1);
})();
- require 引入文件
// ==/UserScript==
下的内容
(function () { 'use strict';console.log(1);})();
的内容
GM_addValueChangeListener
- 先运行监听函数;
- 只要对应名称的值发生变化就可以监听到。
let myname = "user";
GM_addValueChangeListener(myname, function (myname, old_value, new_value, remote) {
console.log(myname, old_value, new_value, remote);
})
let user = {
"a": 1,
"b": 2
};
GM_setValue(myname, user);
function launch1() {
user.a = 2;
GM_setValue(myname, user);
}
function launch2() {
user.c = 3;
GM_setValue(myname, user);
}