// ==UserScript== // @name Coder Utils // @name:en Coder Utils // @namespace http://tampermonkey.net/ // @version 0.1.0 // @description 【使用前先看介绍/有问题可反馈】【欢迎一键三连(好评+打赏+收藏),你的支持是作者维护下去的最大动力!】Coder Utils(程序员专属工具)为程序员专门准备的常用 JavaScript 函数;目前已有:发送请求、下载文件、文本复制;脚本定义的所有函数被定义于 location.utils 中,具体函数使用说明请参照脚本代码详情页。 // @description:en 【使用前先看介绍/有问题可反馈】【欢迎一键三连(好评+打赏+收藏),你的支持是作者维护下去的最大动力!】Coder Utils(程序员专属工具)为程序员专门准备的常用 JavaScript 函数;目前已有:发送请求、下载文件、文本复制;脚本定义的所有函数被定义于 location.utils 中,具体函数使用说明请参照脚本代码详情页。 // @author cc // @include * // @grant none // @downloadURL none // ==/UserScript== (function() { 'use strict'; /** * @brief 发送请求,若请求成功,请求结果将存储于 location.response * @param {string} url 请求 URL * @param {string} params 请求参数,形式为 'k1=v1&k2=v2(&...)',默认为无参数 * @param {string} mode 请求类型,默认为 GET 请求 */ function sendRequest(url, params='', mode='GET') { let request = new XMLHttpRequest(); if (mode == 'GET') { url = `${url}?${encodeURIComponent(params)}`; }; request.open(mode, url, true); request.setRequestHeader('Content-Type', 'application/json'); request.send(params); request.onreadystatechange = function () { if (request.readyState == 4 && request.status == 200) { location.response = request.responseText; }; }; }; /** * @brief 下载 CSV 文件 * @param {string} csvContent CSV 数据,请使用 ',' 分隔数据值,使用 '\n' 分隔数据行,默认为空字符串 * @param {*} fileName 下载的 CSV 文件名,默认为 data.csv */ function downloadCsv(csvContent='', fileName='data.csv') { let pom = document.createElement('a'); let blob = new Blob(['\ufeff' + csvContent], {type: 'text/csv;charset=utf-8;'}); let url = URL.createObjectURL(blob); pom.href = url; pom.setAttribute('download', fileName); document.body.appendChild(pom); pom.click(); document.body.removeChild(pom); }; /** * @brief 将字符串复制至剪切板 * @param {string} content 需要复制到剪切板的内容,默认为空字符串 */ function copyToClipboard(content='') { let textarea = document.createElement('textarea'); textarea.value = content; document.body.appendChild(textarea); textarea.select(); document.execCommand('copy'); document.body.removeChild(textarea); }; // 以上所有函数被定义于 location.utils 中 location.utils = { sendRequest: sendRequest, downloadCsv: downloadCsv, copyToClipboard: copyToClipboard, }; })();