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

说明

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

效果图

直接上代码

javascript 复制代码
// ==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;
  }
})();
相关推荐
console.log('npc')20 小时前
2026前端进阶学习路线
前端·学习
每天都要进步哦20 小时前
React入门和快速上手
前端·vue.js·react.js·react
wuhen_n20 小时前
组件测试策略:测试 Props、事件和插槽
前端·javascript·vue.js
Jiude20 小时前
Skill + MCP + Linear 自动化工作流:让 AI 包揽变更日志工作
前端·架构·cursor
zhensherlock20 小时前
Protocol Launcher 系列:Pika 取色器的协议控制(上篇)
前端·javascript·macos·typescript·github·mac·view design
蚂蚁家的砖20 小时前
基于 Vue 3 + Cesium 的 DJI 无人机航线规划系统技术实践
前端·无人机
inksci20 小时前
推荐动态群聊二维码制作工具
前端·javascript·微信小程序
wuhen_n20 小时前
Vue3 单元测试实战:从组合式函数到组件
前端·javascript·vue.js
郑州光合科技余经理1 天前
海外O2O系统源码剖析:多语言、多货币架构设计与二次开发实践
java·开发语言·前端·小程序·系统架构·uni-app·php
arvin_xiaoting1 天前
OpenClaw学习总结_I_核心架构_8:SessionPruning详解
前端·chrome·学习·系统架构·ai agent·openclaw·sessionpruning