Tampermonkey 油猴脚本笔记


Tampermonkey 语法

require 引入文件

  • 引入后相当于在同一个文件内,可直接调用引入文件的函数。

GM_xmlhttpRequest Promise 写法

// GM_xmlhttpRequest GET异步通用模块
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);
      }
    });
  });
}
// GM_xmlhttpRequest POST异步通用模块
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);
      }
    });
  });
}

脚本执行顺序

// @require      file://d:\a.js
// ==/UserScript==
console.log(0);
(function () {
  'use strict';
	console.log(1);
})();
  1. require 引入文件
  2. // ==/UserScript== 下的内容
  3. (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);
// console.log(2);

function launch1() {
  user.a = 2;
  // console.log(user);
  GM_setValue(myname, user);

}

function launch2() {
  user.c = 3;

  GM_setValue(myname, user);
  // console.log("user", user);
}

文章作者: iKnow
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iKnow !
  目录