// ==UserScript== // @name 易班自动发帖网薪经验值 // @namespace https://wechatid.github.io/2024/11/06/Yiban-JSmonkey/ // @version 2.0 // @description 易班自动发贴微社区的脚本,完全自动获取网薪经验值。自动检测内容是否重复,重复即重新输入新的内容内容,易班微社区完全自动发帖脚本,自动获取网薪和经验值 // @match https://s.yiban.cn/userPost/detail // @grant GM_addStyle // @grant GM_xmlhttpRequest // @grant GM_download // @license All rights reserved // ==/UserScript== (function () { "use strict"; let sever = 'http://47.112.3.177:8000'; let SIMINPUTFROM_CONNET_AUTOINCREM = 0; let submits_count = 0; const panel = document.createElement('div'); panel.id = 'floating-panel'; panel.innerHTML = `

易班自动发帖

公告 ▸

公告:欢迎使用易班自动发帖工具,自动发帖零风险100%安全。
点我使用评论脚本
加QQ群获取免费试用额度,群号:912033859 验证密码为:9412

卡密 / 授权
发帖配置
运行状态(发帖20次会自动停止)
`; const body = document.body; body.insertBefore(panel, body.firstChild); GM_addStyle(` /* 面板样式:固定在页面左侧的侧边栏 */ #floating-panel { position: fixed; top: 0; left: 0; width: 250px; /* 保持原有宽度不变 */ height: 100vh; background-color: #fff; border-radius: 0 8px 8px 0; box-shadow: 2px 0 12px rgba(0, 0, 0, 0.15); z-index: 9999; font-family: Arial, sans-serif; transition: transform 0.3s ease; /* 侧边栏展开/收起动画 */ overflow: hidden; display: flex; flex-direction: column; box-sizing: border-box; } #floating-panel, #floating-panel * { box-sizing: border-box; } /* 收起状态:整个侧边栏滑出到屏幕左侧 */ #floating-panel.yiban-side-collapsed { transform: translateX(-100%); } /* 收起/展开按钮:贴在面板右边缘、垂直居中 */ #toggle-panel { position: fixed; top: 50%; left: 250px; /* 与面板宽度一致,紧贴面板右边缘 */ transform: translateY(-50%); z-index: 10000; width: 22px; height: 56px; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 6px; background-color: #007bff; color: #fff; font-family: Arial, sans-serif; font-size: 13px; font-weight: bold; line-height: 1; box-sizing: border-box; border-radius: 0 8px 8px 0; box-shadow: 2px 0 8px rgba(0, 0, 0, 0.2); cursor: pointer; user-select: none; transition: left 0.3s ease, width 0.3s ease, height 0.3s ease, background-color 0.2s ease; } #toggle-panel:hover { background-color: #0056b3; } /* 展开状态下按钮只显示箭头,不显示文字 */ #toggle-panel .toggle-text { display: none; writing-mode: vertical-rl; /* 竖向文字 */ letter-spacing: 2px; white-space: nowrap; } /* 收起后面板滑出屏幕,按钮跟随到屏幕左边缘,并变成竖排文字 + 箭头 */ body.yiban-side-collapsed #toggle-panel { left: 0; width: 28px; height: 142px; } body.yiban-side-collapsed #toggle-panel .toggle-text { display: block; } /* 箭头符号:展开时朝左(点击收起),收起时朝右(点击展开) */ #toggle-panel .toggle-arrow { display: inline-block; transform: rotate(180deg); transition: transform 0.3s ease; } body.yiban-side-collapsed #toggle-panel .toggle-arrow { transform: rotate(0deg); } #floating-panel .header { background-color: #007bff; color: #fff; padding: 8px 10px; border-radius: 0; flex: 0 0 auto; display: flex; flex-direction: row; justify-content: center; align-items: center; } #floating-panel .header h1 { font-size: 16px; margin: 0; } /* 内容区域:占据剩余高度,内容过多时在面板内部滚动 */ #floating-panel .content { padding: 10px; display: block; flex: 1 1 auto; overflow-y: auto; overflow-x: hidden; } /* ---------- 公告(默认收起,点击标题展开) ---------- */ #floating-panel .announcement { background-color: #e6f7ff; border: 1px solid #cfe9fb; border-radius: 6px; margin-bottom: 10px; overflow: hidden; } #floating-panel .announcement-head { display: flex; align-items: center; justify-content: space-between; padding: 6px 8px; font-size: 12px; color: #0b6bb4; cursor: pointer; user-select: none; } #floating-panel .announcement-head:hover { background-color: #d8eefc; } #floating-panel .announcement-arrow { font-size: 11px; transition: transform 0.2s ease; } #floating-panel .announcement.is-open .announcement-arrow { transform: rotate(90deg); } #floating-panel .announcement-body { display: none; padding: 0 8px 6px; } #floating-panel .announcement.is-open .announcement-body { display: block; } #floating-panel .announcement p { margin: 0; font-size: 12px; line-height: 1.4; /* 公告行间距 */ } /* ---------- 分组卡片 ---------- */ #floating-panel .panel-group { background-color: #f7f9fc; border: 1px solid #eceff3; border-radius: 6px; padding: 8px; margin-bottom: 10px; } #floating-panel .panel-group .group-title { font-size: 11px; color: #8a94a6; margin-bottom: 6px; } #floating-panel .panel-group .group-title-hint { color: #e03131; font-size: 10px; } /* ---------- 卡密 / 授权 ---------- */ #floating-panel .key-section { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; } #floating-panel .key-section label { font-size: 12px; color: #333; white-space: nowrap; } #floating-panel .key-section input { flex: 1 1 auto; min-width: 0; padding: 5px 6px; font-size: 12px; border: 1px solid #ccc; border-radius: 5px; } #floating-panel .key-section button { flex: 0 0 auto; padding: 6px 10px; font-size: 12px; background-color: #007bff; color: #fff; border: none; border-radius: 5px; cursor: pointer; } #floating-panel .key-section button:hover { background-color: #0056b3; } #floating-panel .promo-box { display: flex; align-items: center; justify-content: space-between; gap: 8px; } /* 剩余次数:与加QQ群/购买卡密同一行,靠左对齐 */ #floating-panel .remaining-item { display: flex; align-items: center; flex: 0 0 auto; min-width: 0; } #floating-panel .remaining-item label { margin-right: 6px; font-size: 12px; color: #333; white-space: nowrap; } #floating-panel .remaining-item input { width: 52px; padding: 2px 4px; text-align: center; font-size: 12px; color: #0b6bb4; background-color: #fff; border: 1px solid #dbe3ec; border-radius: 4px; } #floating-panel .promo-links { display: flex; align-items: center; gap: 8px; } #floating-panel .promo-link { font-size: 11px; color: #007bff; text-decoration: none; white-space: nowrap; } #floating-panel .promo-link:hover { text-decoration: underline; } /* ---------- 状态数值 ---------- */ #floating-panel .status { display: flex; align-items: center; justify-content: space-between; gap: 8px; } #floating-panel .status-item { display: flex; align-items: center; flex: 1 1 0; min-width: 0; } #floating-panel .status-item label { margin-right: 6px; font-size: 12px; color: #333; white-space: nowrap; } #floating-panel .status-item input { flex: 1 1 auto; width: auto; min-width: 0; padding: 2px 4px; text-align: center; font-size: 12px; color: #0b6bb4; background-color: #fff; border: 1px solid #dbe3ec; border-radius: 4px; } #floating-panel .run-tip { font-size: 11px; color: #8a94a6; margin-top: 4px; word-break: break-all; } #floating-panel .run-tip:empty { display: none; } /* ---------- 开始/停止运行按钮 ---------- */ #floating-panel .run-control { margin-top: 8px; } #floating-panel .run-toggle-btn { width: 100%; padding: 10px 0; font-size: 14px; font-weight: bold; font-family: Arial, sans-serif; color: #fff; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; justify-content: center; gap: 8px; letter-spacing: 2px; transition: background-color 0.25s ease, box-shadow 0.25s ease, transform 0.15s ease; } #floating-panel .run-toggle-btn:active { transform: scale(0.97); } /* 开始:绿色渐变 */ #floating-panel .run-toggle-btn.run-start { background: linear-gradient(135deg, #3ecf6e 0%, #22a355 100%); box-shadow: 0 4px 12px rgba(46, 204, 113, 0.4); } #floating-panel .run-toggle-btn.run-start:hover { background: linear-gradient(135deg, #4ddc7d 0%, #27b361 100%); box-shadow: 0 6px 16px rgba(46, 204, 113, 0.55); } /* 停止:红色渐变 */ #floating-panel .run-toggle-btn.run-stop { background: linear-gradient(135deg, #ff6b6b 0%, #e03131 100%); box-shadow: 0 4px 12px rgba(224, 49, 49, 0.4); } #floating-panel .run-toggle-btn.run-stop:hover { background: linear-gradient(135deg, #ff7c7c 0%, #ec3d3d 100%); box-shadow: 0 6px 16px rgba(224, 49, 49, 0.55); } #floating-panel .run-toggle-icon { font-size: 12px; line-height: 1; } /* ---------- 发帖配置 ---------- */ #floating-panel .config-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; } #floating-panel .config-row label { font-size: 12px; color: #333; white-space: nowrap; } #floating-panel .custom-select { width: 60%; max-width: 140px; padding: 4px; margin: 0; font-size: 12px; border: 2px solid #ff9900; border-radius: 4px; background-color: #fff; } /* ---------- 底部操作区(后续「启动执行」按钮的挂载位置) ---------- */ #floating-panel .panel-footer { flex: 0 0 auto; padding: 8px 10px; border-top: 1px solid #eceff3; background-color: #fff; } #floating-panel .panel-footer:empty { display: none; } #floating-panel .panel-footer button { width: 100%; padding: 8px 0; font-size: 13px; color: #fff; background-color: #007bff; border: none; border-radius: 5px; cursor: pointer; } #floating-panel .panel-footer button:hover { background-color: #0056b3; } `); // 侧边栏展开和收起功能(默认为展开) // 收起/展开按钮:贴在面板右边缘、垂直居中,符号为 > const toggleButton = document.createElement('div'); toggleButton.id = 'toggle-panel'; toggleButton.innerHTML = '发帖脚本面板>'; body.appendChild(toggleButton); let isCollapsed = false; function setSideCollapsed(collapsed) { isCollapsed = collapsed; panel.classList.toggle('yiban-side-collapsed', collapsed); body.classList.toggle('yiban-side-collapsed', collapsed); toggleButton.title = collapsed ? '展开面板' : '收起面板'; } toggleButton.title = '收起面板'; toggleButton.addEventListener('click', () => { setSideCollapsed(!isCollapsed); }); // 说明:面板已改为固定在页面左侧的侧边栏,原拖动功能不再适用(纯界面调整,不影响任何业务逻辑) // 公告折叠:默认收起,点击标题展开/收起(纯界面交互) const announcementBox = document.getElementById('panel-announcement'); document.getElementById('announcement-head').addEventListener('click', () => { announcementBox.classList.toggle('is-open'); }); // 从 localStorage 中读取保存的 API Key let savedKey = localStorage.getItem('apiKey'); if (savedKey) { // 如果有保存的API Key,将其填充到输入框 document.getElementById('api-key').value = savedKey; } else { document.getElementById('api-key').placeholder = "暂未填写你的卡密"; } // 获取确认按钮并添加事件监听器 document.getElementById('submit-btn').addEventListener('click', function () { // 获取用户输入的 API Key const apiKey = document.getElementById('api-key').value; if (apiKey) { // 存储用户输入的 API Key 到 localStorage localStorage.setItem('apiKey', apiKey); savedKey = localStorage.getItem('apiKey'); document.getElementById('api-key').value = savedKey; alert('卡密已保存,请妥善保管,清除缓存会丢失卡密信息!点击「开始运行」即可开始'); } else { //alert('请输入有效的API Key'); } }); let input = document.getElementById('remaining'); GM_xmlhttpRequest({ method: 'GET', url: sever + '/check_counter?key=' + savedKey, headers: { 'Accept': 'application/json' }, onload: function (r) { if (r.status === 200) { try { const j = JSON.parse(r.responseText); input.value = j.counter; } catch (e) { input.value = '响应解析失败'; } } else { input.value = '卡密不存在'; } }, onerror: function () { input.value = '请求失败'; } }); let msgtype = localStorage.getItem('msgtype'); let selectopt = document.getElementById('mySelect'); if (msgtype) { setSelectValue(msgtype); } else { const selectedOption = selectopt.options[selectopt.selectedIndex]; selectedOption.value = "poem"; localStorage.setItem('msgtype', "poem"); } // 实时监听函数 function updateSelection() { const selectedOption = selectopt.options[selectopt.selectedIndex]; // 显示完整选择信息 //feedbackElement.textContent = `已选择:${selectedOption.text} (值:${selectedOption.value})`; const type = selectedOption.value localStorage.setItem('msgtype', type); msgtype = localStorage.getItem(type); //setSelectValue(msgtype); } // 事件监听 selectopt.addEventListener('change', updateSelection); function setSelectValue(value) { const selectElement = document.getElementById('mySelect'); const validValues = ['poem', 'string']; // 有效性验证 if (!validValues.includes(value)) { console.warn(`无效值:${value},可用值:${validValues.join(', ')}`); return false; } // 设置选中状态 let found = false; Array.from(selectElement.options).forEach(option => { if (option.value === value) { option.selected = true; found = true; } else { option.selected = false; } }); // 触发事件 if (found) { selectElement.dispatchEvent(new Event('change')); return true; } return false; } function simulateComplexClick(element, offsetX, offsetY) { let rect = element.getBoundingClientRect(); let click_x = rect.left + offsetX; let click_y = rect.top + offsetY; ["mousedown", "mouseup", "click", /* "touchstart"*/ ].forEach((eventType) => { var clickEvent = new MouseEvent("mousedown", { bubbles: true, cancelable: true, view: unsafeWindow, clientX: click_x, clientY: click_y, }); element.dispatchEvent(clickEvent); let td; let td_s = setInterval(() => { if (!isRunning) { clearInterval(td_s); return; } //发帖成功之后的页面按钮 td = document.querySelector("body > div.container > section > div.mdc-alert.mdc-alert--success > div"); if (td == null) { console.log('检测不到'); verify(); clearInterval(td_s); } clearInterval(td_s); }, 4000); }); } function waitForElement(selector, timeout = 3000) { return new Promise((resolve, reject) => { const startTime = Date.now(); // 定时器检查元素是否存在 const msgIsRepeat_int = setInterval(() => { const msgIsRepeat = document.querySelector(selector); if (msgIsRepeat) { clearInterval(msgIsRepeat_int); // 找到元素时清除定时器 resolve(msgIsRepeat); // 返回元素 } // 如果超过指定的时间还没找到元素 if (Date.now() - startTime > timeout) { clearInterval(msgIsRepeat_int); // 超时时清除定时器 reject(new Error(`Element not found within ${timeout} ms`)); // 返回超时错误 } }, 200); // 每100毫秒检查一次 }); } window.simulateComplexClick = simulateComplexClick let bg_url = ''; // 全局状态变量,存储背景图 URL let interval; // 用于保存定时器引用 function verify() { if (!isRunning) { return; } // 清除之前的定时器 if (interval) { clearInterval(interval); interval = null; } setTimeout(() => { interval = setInterval(() => { //let element = document.querySelector('.shumei_captcha_loaded_img_bg'); let base_dom = document.querySelector("body").lastChild.childNodes[1].childNodes[0]; waitForElement('body > div.mdc-confirm-dialog.mdc-dialog.mdc-dialog--open > div.mdc-dialog__container > div > footer > button.mdc-button.mdc-button--outlined.mdc-confirm-dialog__secondary-button') .then(msgIsRepeat => { console.log('Element found:', msgIsRepeat); clearInterval(interval); interval = null; msgIsRepeat.click(); SIMINPUTFROM_CONNET_AUTOINCREM--; edit_text(); return; // 在这里处理找到的元素 }) .catch(error => { console.log(error.message); // 处理没有找到元素的情况(比如超时) }); let element = base_dom.childNodes[0].childNodes[2].firstChild.firstChild; let msgIsRepeat; // msgIsRepeat = document.querySelector("body > div.mdc-confirm-dialog.mdc-dialog.mdc-dialog--open > div.mdc-dialog__container > div > footer > button.mdc-button.mdc-button--outlined.mdc-confirm-dialog__secondary-button"); if (element) { console.log("检测验证码是否弹出"); // 检查 src 是否更新 if (element.src.indexOf('https') !== -1 && bg_url !== element.src) { clearInterval(interval); interval = null; // 清除定时器,防止重复执行 bg_url = element.src; // 更新 bg_url GM_xmlhttpRequest({ method: 'GET', url: sever + '/predict?key=' + savedKey + '&bg_img=' + encodeURIComponent(element.src), headers: { 'Accept': 'application/json' }, onload: function (r) { if (r.status === 200) { try { const j = JSON.parse(r.responseText); if (j['reply'] === 'success') { simulateComplexClick(base_dom.childNodes[0].childNodes[2].firstChild.firstChild, j['position']['X'] / 2, j['position']['Y'] / 2); input.value = j['counter']; } else { alert('次数不够'); } } catch (e) { alert('响应解析失败'); } } else { alert('卡密或者服务器错误'); } }, onerror: function () { alert('请求失败'); } }); } } }, 100); }, 100); } window.edit_text = function() { if (!isRunning) { return; } // 定义需要查找的核心元素选择器(便于维护) const selectors = { input1: "body > div.container > section > div.mdc-form.mdc-form--horizontal > div:nth-child(1) > div > input", input2: "body > div.container > section > div.mdc-form.mdc-form--horizontal > div:nth-child(2) > div > span.mdc-text-field__resizer > textarea", submitBtn: "body > div.container > section > div.actions > div > button:nth-child(2) > div" }; let msgtype = localStorage.getItem('msgtype'); // 轮询最大次数(避免无限循环,可根据页面加载速度调整) const MAX_RETRY = 20; let retryCount = 0; // 封装:获取核心DOM元素 const getCoreElements = () => { const input_1 = document.querySelector(selectors.input1); const input_2 = document.querySelector(selectors.input2); // 动态ID的UEditor元素 const ueditorIframe = document.getElementById(`ueditor_${SIMINPUTFROM_CONNET_AUTOINCREM}`); const connet = ueditorIframe?.contentWindow.document.querySelector("body > p"); const submit_btn = document.querySelector(selectors.submitBtn); return { input_1, input_2, connet, submit_btn, ueditorIframe }; }; // 封装:提交表单逻辑 const submitForm = (submit_btn) => { SIMINPUTFROM_CONNET_AUTOINCREM++; if (submit_btn) { setTimeout(() => { submit_btn.click(); verify(); // 假设verify是已定义的验证函数 }, 300); // 短延迟确保事件触发完成 } else { console.error("提交按钮未找到"); } }; // 封装:填充+提交的核心逻辑(元素加载完成后执行) const executeLogic = () => { const { input_1, input_2, connet, submit_btn } = getCoreElements(); // 最终检查:元素仍不存在则终止 if (!input_1 || !input_2 || !connet || !submit_btn) { console.error("核心元素加载失败,终止操作"); alert("页面元素加载失败,请刷新页面重试"); return; } // ========== 原有填充逻辑 ========== if (msgtype == "poem") { GM_xmlhttpRequest({ method: "GET", url: "https://v1.hitokoto.cn/", onload: function(response) { try { const data = JSON.parse(response.responseText); let info_text = data.hitokoto; let from = data.from || "未知出处"; let author = data.from_who || "未知作者"; // 填充内容 input_1.value = info_text; input_2.value = info_text; connet.innerHTML = `

${info_text}

来自:${from}

作者:${author}

`; // 触发input事件 const event = new Event('input', { bubbles: true, cancelable: true }); event.eventType = "message"; [input_1, input_2, connet].forEach(el => el.dispatchEvent(event)); // 填充完成后提交 submitForm(submit_btn); } catch (e) { console.error("数据处理失败:", e); alert('文案接口异常,请切换字母数字组合使用'); } }, onerror: function(error) { console.error("请求失败:", error); alert('文案接口异常,请切换字母数字组合使用'); } }); } else if (msgtype == "string") { // 生成随机字符串 let s = ''; for (let i = 0; i < 26; i++) { s += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'[Math.random() * 36 | 0]; } // 填充内容 input_1.value = s; input_2.value = s; connet.innerHTML = `

${s}

`; // 触发input事件 const event = new Event('input', { bubbles: true, cancelable: true }); event.eventType = "message"; [input_1, input_2, connet].forEach(el => el.dispatchEvent(event)); // 填充完成后提交 submitForm(submit_btn); } }; // ========== 核心:轮询等待DOM元素加载 ========== const checkElementLoaded = () => { const { input_1, input_2, connet, submit_btn } = getCoreElements(); // 元素全部找到 → 执行逻辑 if (input_1 && input_2 && connet && submit_btn) { executeLogic(); } else { retryCount++; // 未找到且未超时 → 继续轮询(每300ms检查一次) if (retryCount < MAX_RETRY) { setTimeout(checkElementLoaded, 300); } else { // 超时 → 终止并提示 console.error(`轮询${MAX_RETRY}次后仍未找到核心元素`); alert("页面加载超时,请刷新页面后重试"); } } }; // 启动轮询 checkElementLoaded(); }; window.scan_succeed = function () { let d; let _t = setInterval(() => { if (!isRunning) { clearInterval(_t); return; } d = document.querySelector("body > div.container > section > div.mdc-alert.mdc-alert--success > div"); if (d != null) { submits_count++; if (submits_count >= 20) { document.querySelector("head > title").innerHTML = "已完成! "; clearInterval(_t); } else { wait_cd(); clearInterval(_t); } } }, 1000); }; window.wait_cd = function () { let t = 60; let _t = setInterval(() => { if (!isRunning) { clearInterval(_t); return; } document.querySelector("head > title").innerHTML = `🎉 ${String(submits_count)} / ${String(t)}`; document.getElementById('posted').value = submits_count; t = t - 1; if (t == 0) { wait_cd_after(); document.querySelector("head > title").innerHTML = "😴 等待验证口令..."; clearInterval(_t); } }, 1000); }; window.wait_cd_after = function () { if (!isRunning) { return; } let continueTo = document.querySelector( "body > div.container > section > div.mdc-alert.mdc-alert--success > div > p > a:nth-child(2) > div.mdc-button__ripple" ); continueTo.click(); setTimeout(() => { edit_text(); scan_succeed(); }, 1000); }; // 运行开关:默认不自动执行,必须点击「开始运行」按钮才会启动脚本逻辑 let isRunning = false; function stopRunLogic() { // 停止所有可能的定时器与后续链路 if (interval) { clearInterval(interval); interval = null; } try { document.querySelector("head > title").innerHTML = "已停止"; } catch (e) { /* 忽略 */ } } const runToggleBtn = document.getElementById('run-toggle-btn'); const runToggleText = runToggleBtn.querySelector('.run-toggle-text'); const runToggleIcon = runToggleBtn.querySelector('.run-toggle-icon'); function updateRunButtonUI() { runToggleBtn.classList.toggle('run-start', !isRunning); runToggleBtn.classList.toggle('run-stop', isRunning); runToggleText.textContent = isRunning ? '停止' : '开始运行'; runToggleIcon.innerHTML = isRunning ? '■' : '▶'; } runToggleBtn.addEventListener('click', function () { if (!isRunning) { if (!savedKey) { alert('请先输入并保存卡密,再点击开始运行'); return; } isRunning = true; updateRunButtonUI(); edit_text(); scan_succeed(); } else { isRunning = false; updateRunButtonUI(); stopRunLogic(); } }); function w1t67rL1() { let pW7x = 5; let vB8j = 10; return pW7x + vB8j; } function z3lT9r0A(a, b) { let Y0i9p = a * b; let qN2u9s = Y0i9p / 2; return Y0i9p - qN2u9s; } function dB3J2wK() { let H7f = [1, 2, 3, 4, 5]; H7f.push(6); H7f.pop(); return H7f.length; } function tR8c2N(value) { let k0j = { a: 1, b: 2, c: 3 }; let f6d = k0j[value]; return f6d; } function qT5w3X() { let M9b = "hello"; let F7g = "world"; return M9b + F7g; } function nW8r1Z() { let o8Q = 100; for (let z3p = 0; z3p < o8Q; z3p++) { Math.random(); } return null; } function s1M9l3P(str) { let vQ9a = ''; for (let i = 0; i < str.length; i++) { vQ9a += str.charAt(i); } let reversed = vQ9a.split('').reverse().join(''); return reversed === vQ9a ? true : false; } // ====================================================================== // 【本次新增功能】发帖范围 / 版块 的选择与自动应用 // ---------------------------------------------------------------------- // 说明(纯新增,不改动上方任何原有变量、函数与流程): // 1. 数据来源与 Python 端保持一致(易班官方接口): // GET https://s.yiban.cn/api/org/getMyOrgs -> 发布范围 // GET https://s.yiban.cn/api/board/list?orgId=xxx -> 版块 // Cookie 由 GM_xmlhttpRequest 自动携带(当前浏览器登录态)。 // 2. 选择结果保存在 localStorage: // yiban_post_org { id, name } // yiban_post_board { id, name } // yiban_post_auto_select "1" / "0" // 3. 页面发帖表单里存在原生下拉框(label「发布范围:」「选择版块:」 // + select.custom-select),本功能只负责把保存的值写进去。 // ====================================================================== (function initPostSelectFeature() { "use strict"; const ORG_LIST_API = "https://s.yiban.cn/api/org/getMyOrgs"; const BOARD_LIST_API = "https://s.yiban.cn/api/board/list"; const STORE_ORG = "yiban_post_org"; const STORE_BOARD = "yiban_post_board"; const STORE_AUTO = "yiban_post_auto_select"; // ---------- 1. 新增样式(独立调用,不影响原有 GM_addStyle) ---------- GM_addStyle(` #floating-panel .yiban-opt-box { margin-top: 8px; margin-bottom: 0; } #floating-panel .yiban-opt-box label { display: block; font-size: 12px; margin-bottom: 4px; color: #333; } #floating-panel .yiban-opt-select { width: 100%; padding: 4px; font-size: 12px; background: white; border: 2px solid #ff9900; border-radius: 5px; margin-bottom: 6px; } #floating-panel .yiban-opt-select:disabled { opacity: 0.6; } #floating-panel .yiban-opt-row { display: flex; gap: 6px; } #floating-panel .yiban-opt-btn { flex: 1; padding: 6px 0; font-size: 12px; border: 1px solid #007bff; border-radius: 5px; background: #fff; color: #007bff; cursor: pointer; } #floating-panel .yiban-opt-btn:hover { background: #eaf3ff; } #floating-panel .yiban-opt-auto { display: flex; align-items: center; font-size: 12px; margin-top: 6px; } #floating-panel .yiban-opt-auto input { width: auto; margin: 0; } #floating-panel .yiban-opt-auto label { display: inline; margin: 0 0 0 5px; } #floating-panel .yiban-opt-tip { font-size: 11px; color: #888; margin-top: 4px; min-height: 14px; word-break: break-all; } `); const panelContentEl = document.querySelector("#floating-panel .content"); if (!panelContentEl) { return; } // ---------- 2. localStorage 读写 ---------- const readSaved = function (key) { try { const raw = localStorage.getItem(key); return raw ? JSON.parse(raw) : null; } catch (e) { return null; } }; const writeSaved = function (key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch (e) { /* 忽略存储异常 */ } }; // ---------- 3. 动态插入新增 UI(原有 innerHTML 不做任何改动) ---------- const box = document.createElement("div"); box.className = "yiban-opt-box"; box.innerHTML = `
`; // 挂载到「发帖配置」分组卡片内(仅调整摆放位置,逻辑不变) const configGroupEl = panelContentEl.querySelector("#yiban-post-config"); if (configGroupEl) { configGroupEl.appendChild(box); } else { panelContentEl.appendChild(box); } const orgSelectEl = document.getElementById("yiban-org-select"); const boardSelectEl = document.getElementById("yiban-board-select"); const tipEl = document.getElementById("yiban-opt-tip"); const autoCheckEl = document.getElementById("yiban-auto-check"); const setTip = function (msg) { tipEl.textContent = msg || ""; }; const addOption = function (selectEl, value, text) { const option = document.createElement("option"); option.value = String(value); option.textContent = text; selectEl.appendChild(option); }; const selectedText = function (selectEl) { const option = selectEl.options[selectEl.selectedIndex]; return option ? option.textContent : ""; }; const selectByValue = function (selectEl, value) { const target = String(value); for (let i = 0; i < selectEl.options.length; i++) { if (selectEl.options[i].value === target) { selectEl.selectedIndex = i; return true; } } return false; }; // ---------- 4. 接口请求封装(与 Python 端解析结构一致) ---------- const request = function (url) { return new Promise(function (resolve, reject) { GM_xmlhttpRequest({ method: "GET", url: url, headers: { "Accept": "application/json, text/plain, */*", "platform": "yiban_web" }, timeout: 15000, onload: function (r) { if (r.status !== 200) { reject(new Error("HTTP " + r.status)); return; } let json; try { json = JSON.parse(r.responseText); } catch (e) { reject(new Error("响应解析失败")); return; } if (!json || !json.status) { reject(new Error((json && json.message) || "接口返回失败")); return; } resolve(json.data); }, onerror: function () { reject(new Error("网络请求失败")); }, ontimeout: function () { reject(new Error("请求超时")); } }); }); }; // ---------- 5. 加载发布范围 ---------- const loadOrgs = function () { orgSelectEl.disabled = true; setTip("正在加载发布范围..."); request(ORG_LIST_API).then(function (data) { orgSelectEl.innerHTML = ""; addOption(orgSelectEl, "", "默认(不修改)"); const groups = Array.isArray(data) ? data : []; groups.forEach(function (group) { const orgTypeName = (group && group.orgTypeName) || ""; const list = (group && group.list) || []; list.forEach(function (org) { addOption(orgSelectEl, org.orgId, "【" + orgTypeName + "】" + (org.name || org.orgId)); }); }); // 回填已保存的选择(若接口列表中已不存在,则补充一条占位项) const savedOrg = readSaved(STORE_ORG); if (savedOrg && savedOrg.id !== undefined && savedOrg.id !== "") { if (!selectByValue(orgSelectEl, savedOrg.id)) { addOption(orgSelectEl, savedOrg.id, (savedOrg.name || savedOrg.id) + "(已保存)"); selectByValue(orgSelectEl, savedOrg.id); } } orgSelectEl.disabled = false; setTip("发布范围加载完成,共 " + Math.max(orgSelectEl.options.length - 1, 0) + " 项"); onOrgChange(); }).catch(function (err) { orgSelectEl.disabled = false; setTip("发布范围加载失败:" + err.message); }); }; // ---------- 6. 加载版块 ---------- const loadBoards = function (orgId) { if (!orgId) { return; } boardSelectEl.innerHTML = ""; addOption(boardSelectEl, "", "默认(不修改)"); boardSelectEl.disabled = true; setTip("正在加载版块..."); request(BOARD_LIST_API + "?orgId=" + encodeURIComponent(orgId)).then(function (data) { const list = Array.isArray(data) ? data : []; list.forEach(function (board) { addOption(boardSelectEl, board.id, board.name || board.id); }); const savedBoard = readSaved(STORE_BOARD); if (savedBoard && savedBoard.id !== undefined && savedBoard.id !== "") { if (!selectByValue(boardSelectEl, savedBoard.id)) { // 保存的版块不属于当前范围,丢弃,避免误选 localStorage.removeItem(STORE_BOARD); boardSelectEl.selectedIndex = 0; } } boardSelectEl.disabled = false; setTip("版块加载完成,共 " + Math.max(boardSelectEl.options.length - 1, 0) + " 项"); }).catch(function (err) { boardSelectEl.disabled = false; setTip("版块加载失败:" + err.message); }); }; // ---------- 7. 选择变化时持久化 ---------- const onOrgChange = function () { if (orgSelectEl.value) { writeSaved(STORE_ORG, { id: orgSelectEl.value, name: selectedText(orgSelectEl) }); } else { localStorage.removeItem(STORE_ORG); } loadBoards(orgSelectEl.value); }; orgSelectEl.addEventListener("change", onOrgChange); boardSelectEl.addEventListener("change", function () { if (boardSelectEl.value) { writeSaved(STORE_BOARD, { id: boardSelectEl.value, name: selectedText(boardSelectEl) }); } else { localStorage.removeItem(STORE_BOARD); } }); autoCheckEl.addEventListener("change", function () { localStorage.setItem(STORE_AUTO, autoCheckEl.checked ? "1" : "0"); }); document.getElementById("yiban-refresh-btn").addEventListener("click", function () { loadOrgs(); }); document.getElementById("yiban-apply-btn").addEventListener("click", function () { applyToPage(true); }); // ---------- 8. 定位页面上的原生 select ---------- // 页面结构: