// ==UserScript== // @name 监测汇率每日变化 // @namespace wyx // @description 美元现汇卖出价 // @version 0.0.1 // @author wyx // @crontab * 10-23 once * * // @grant GM_xmlhttpRequest // @grant GM_notification // @grant GM_getValue // @grant GM_setValue // @connect chl.cn // @connect sct.icodef.com // @require https://scriptcat.org/lib/946/%5E1.0.1/PushCat.js // ==/UserScript== let accessKey = GM_getValue("PushCat.AccessKey"); // //* 消息推送: https://sct.icodef.com/ const push = new PushCat({ accessKey, }); //* 返回的是一个函数体 function pushSend(title, content) { return new Promise(resolve => { if (accessKey) { push.send(title, content); } // 启用浏览器的通知功能 GM_notification({ title: title, text: content, }); resolve(); }) } // 功能函数,获取子串,获取包含在html内的json数据 function getSubstring(inputStr, startStr, endStr) { const startIndex = inputStr.indexOf(startStr); if (startIndex == -1) { return null; } const endIndex = inputStr.indexOf(endStr, startIndex + startStr.length); if (endIndex == -1) { return null; } return inputStr.substring(startIndex + startStr.length, endIndex); } function getChangeRateInfo() { return new Promise((resolve, reject) => { // 获取汇率网站信息 GM_xmlhttpRequest({ url:'https://chl.cn/?usd', onload(resp) { if (resp.status == 200) { resolve(resp); } else { // 获取失败,在此尝试 pushSend("汇率获取失败", "请求返回错误: " + resp.status).then(() => reject()); } }, onerror(e) { pushSend("汇率获取失败", e || "未知错误").then(() => reject()); } }); }) } // 主要功能函数 function handler() { return getChangeRateInfo().then(async resp => { // 获取的数据是存在html中 const data = resp.responseText; const startStra = ""; // 拆分html文本中的数据 var tableStra = getSubstring(data,startStra,endStra) // 拼接 table 标签文本 tableStra = startStra + tableStra + endStra ; // 创建 DOM 解析器实例 const parser = new DOMParser(); // 使用解析器解析文本并获取根元素 const document = parser.parseFromString(tableStra, 'text/html'); const table = document.getElementsByTagName('table')[0]; if (table.rows.length >3){ const row = table.rows[2]; var cell = row.cells[4]; // 现汇卖出价: const spots = cell.textContent.trim(); cell = row.cells[2]; // 现汇买入价: const spotb = cell.textContent.trim(); await pushSend('今日美元汇率','现汇卖出价: '+ spots +' \n现汇买入价: '+spotb) return true; }else{ await pushSend('汇率数据解析失败','解析数据出错,请核对网站数据结构是否发生变化') return true; } }); } // 文件执行的入口 return new Promise((resolve, reject) => { const h = async () => { try { const result = await handler(); if (result) { resolve(); } else { // 定时循环调用 h(),确保所有任务都能完成 setTimeout(() => { h(); }, 1000 * (Math.floor(Math.random() * 4) + 10)); } } catch (e) { pushSend('汇率获取失败', '请查看错误日志手动重试'); reject(e); } } // 程序入口调用 h(); });