谷歌浏览器自定义油猴插件

0 阅读1分钟

说明

本例子是在页面加载一个按钮,点击后调用接口,可有get和post请求

效果图

image.png

image.png

直接上代码

// ==UserScript==
// @name         洗刷刷
// @namespace    http://tampermonkey.net/
// @icon         https://static.yuanbao.tencent.com/m/yuanbao-web/favicon@32.png
// @version      0.1
// @description  洗刷刷
// @author       wangwang
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @match        *://*/*
// ==/UserScript==

(function () {
  "use strict";
  // 封装GM_xmlhttpRequest为Promise
  function request(method, url, data = null) {
    return new Promise((resolve, reject) => {
      const options = {
        method: method,
        url: url,
        onload: function (response) {
          try {
            const data = JSON.parse(response.responseText);
            resolve(data);
          } catch (e) {
            resolve(response.status);
          }
        },
        onerror: function (error) {
          reject(new Error(`请求失败: ${error.statusText || "网络错误"}`));
        },
        ontimeout: function () {
          reject(new Error("请求超时"));
        }
      };
      // 如果是POST请求且有数据,则设置请求体
      if (method.toUpperCase() === "POST" && data) {
        if (typeof data === "object") {
          options.data = JSON.stringify(data);
          options.headers = {
            "Content-Type": "application/json"
          };
        } else {
          options.data = data;
        }
      }
      GM_xmlhttpRequest(options);
    });
  }
  // GET请求函数
  function xzwget(url, params = null) {
    if (params && typeof params === "object") {
      const queryString = Object.keys(params)
        .map(
          (key) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`
        )
        .join("&");
      url = url + (url.includes("?") ? "&" : "?") + queryString;
    }
    return request("GET", url);
  }
  // POST请求函数
  function xzwpost(url, data = null) {
    return request("POST", url, data);
  }
  // 创建一个按钮
  function createButton() {
    const button = document.createElement("button");
    button.innerHTML = "高级功能";
    button.style.position = "fixed";
    button.style.top = "10px";
    button.style.right = "10px";
    button.style.zIndex = "9999";
    button.style.padding = "10px";
    button.style.backgroundColor = "#4CAF50";
    button.style.color = "white";
    button.style.border = "none";
    button.style.borderRadius = "5px";
    button.style.cursor = "pointer";
    button.addEventListener("click", function () {
      console.log(document.title);
      xzwget("https://randomuser.me/api/?results=10", {})
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    });
    document.body.appendChild(button);
  }
  // 页面加载完成后创建按钮
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", createButton);
  } else {
    createButton()
    unsafeWindow.request = request;
    unsafeWindow.xzwget = xzwget;
    unsafeWindow.xzwpost = xzwpost;
  }
})();