// ==UserScript== // @name JLC_SHOP_SEARCH_TOOL_2.0 // @namespace http://tampermonkey.net/ // @version 2.6.0 // @description 立创商城搜索页助手2.0(MRO 增强 + 新版品牌面板;点已选品牌可只看它) // @author Lx // @match https://so.szlcsc.com/global.html** // @match https://list.szlcsc.com/brand/** // @match https://list.szlcsc.com/catalog** // @match https://list.szlcsc.com/mro/** // @match https://so.szlcsc.com/mro/** // @match https://mro.szlcsc.com/** // @require https://raw.giteeusercontent.com/mlx6_admin/public_resource_lc/raw/master/public/jquery-351.js // @grant GM_xmlhttpRequest // @grant GM_openInTab // @grant GM_setValue // @grant GM_getValue // @connect szlcsc.com // @connect scriptcat.org // @license MIT // ==/UserScript== /** * Message 全局消息通知组件 * 使用方式: * window.$message.success('操作成功') * window.$message.error('操作失败') * window.$message.warning('警告信息') * window.$message.info('普通信息') */ (function(window) { // 样式定义 const style = ` .message-container { position: fixed; top: 20px; left: 0; right: 0; display: flex; flex-direction: column; align-items: center; pointer-events: none; z-index: 1000000000000000000; } .message-item { min-width: 300px; max-width: 600px; padding: 8px 20px; margin-bottom: 10px; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); background: #fff; transition: all 0.3s; display: flex; align-items: center; pointer-events: auto; overflow: hidden; } .message-item.success { background-color: #f0f9eb; color: #67c23a; border: 1px solid #e1f3d8; } .message-item.error { background-color: #fef0f0; color: #f56c6c; border: 1px solid #fde2e2; } .message-item.warning { background-color: #fdf6ec; color: #e6a23c; border: 1px solid #faecd8; } .message-item.info { background-color: #edf2fc; color: #909399; border: 1px solid #ebeeef; } .message-icon { margin-right: 10px; font-size: 18px; } .message-content { flex: 1; font-size: 14px; line-height: 1.5; } .message-close { margin-left: 15px; color: #c0c4cc; cursor: pointer; font-size: 16px; } .message-close:hover { color: #909399; } .message-fade-enter-active, .message-fade-leave-active { transition: all 0.3s; } .message-fade-enter, .message-fade-leave-to { opacity: 0; transform: translateY(-20px); } `; // 添加样式到head const styleElement = document.createElement('style'); styleElement.innerHTML = style; document.head.appendChild(styleElement); // 消息队列 let messages = []; let container = null; // 创建消息容器 function createContainer() { if (!container) { container = document.createElement('div'); container.className = 'message-container'; document.body.appendChild(container); } return container; } // 创建消息元素 function createMessage(type, message, duration = 3000) { const container = createContainer(); const messageId = Date.now() + Math.random().toString(36).substr(2, 9); const messageEl = document.createElement('div'); messageEl.className = `message-item ${type}`; messageEl.dataset.id = messageId; // 图标 const iconMap = { success: '✓', error: '✕', warning: '⚠', info: 'ℹ' }; const iconEl = document.createElement('span'); iconEl.className = 'message-icon'; iconEl.textContent = iconMap[type] || ''; // 内容 const contentEl = document.createElement('span'); contentEl.className = 'message-content'; contentEl.textContent = message; // 关闭按钮 const closeEl = document.createElement('span'); closeEl.className = 'message-close'; closeEl.innerHTML = '×'; closeEl.onclick = () => removeMessage(messageId); messageEl.appendChild(iconEl); messageEl.appendChild(contentEl); messageEl.appendChild(closeEl); // 添加到DOM container.appendChild(messageEl); // 触发动画 setTimeout(() => { messageEl.style.opacity = '1'; messageEl.style.transform = 'translateY(0)'; }, 10); // 自动关闭 if (duration > 0) { setTimeout(() => { removeMessage(messageId); }, duration); } // 添加到消息队列 messages.push({ id: messageId, element: messageEl }); return messageId; } // 移除消息 function removeMessage(id) { const index = messages.findIndex(msg => msg.id === id); if (index === -1) return; const { element } = messages[index]; // 触发离开动画 element.style.opacity = '0'; element.style.transform = 'translateY(-20px)'; // 动画结束后移除 setTimeout(() => { if (element.parentNode) { element.parentNode.removeChild(element); } // 从队列中移除 messages.splice(index, 1); // 如果没有消息了,移除容器 if (messages.length === 0 && container) { document.body.removeChild(container); container = null; } }, 300); } // 清除所有消息 function clearAll() { messages.forEach(msg => { if (msg.element.parentNode) { msg.element.parentNode.removeChild(msg.element); } }); messages = []; if (container) { document.body.removeChild(container); container = null; } } // 导出到全局 window.$message = { success: (message, duration) => createMessage('success', message, duration), error: (message, duration) => createMessage('error', message, duration), warning: (message, duration) => createMessage('warning', message, duration), info: (message, duration) => createMessage('info', message, duration), closeAll: clearAll }; // ===== 进度条组件:用于「批量勾选品牌」等耗时操作 ===== // 优先挂在三色按钮那一行的右侧空白(#_remind / #_mro_remind), // 找不到容器时回退到底部固定,保证任何页面都能看到进度。 const progressStyle = ` .jlc-progress { display: inline-flex; align-items: center; gap: 8px; margin-left: auto; padding: 3px 8px; border: 1px solid #E5E8EC; border-radius: 4px; background: #fff; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 12px; color: #444; white-space: nowrap; } .jlc-progress.jlc-progress-fixed { position: fixed; bottom: 96px; left: 50%; transform: translateX(-50%); z-index: 1000000000000000000; margin-left: 0; width: 320px; padding: 12px 16px; box-shadow: 0 4px 16px rgba(0,0,0,0.12); } .jlc-progress-label { display: inline-flex; align-items: center; gap: 8px; } .jlc-progress-count { color: #0093E6; font-weight: 500; } .jlc-progress-track { width: 100px; height: 6px; border-radius: 3px; background: #F0F2F5; overflow: hidden; } .jlc-progress.jlc-progress-fixed .jlc-progress-track { width: auto; flex: 1; } .jlc-progress-fill { height: 100%; width: 0%; border-radius: 3px; background: #0093E6; transition: width 0.12s linear; } `; const progressStyleEl = document.createElement('style'); progressStyleEl.innerHTML = progressStyle; document.head.appendChild(progressStyleEl); let progressEl = null; function ensureProgressEl() { if (!progressEl) { progressEl = document.createElement('div'); progressEl.className = 'jlc-progress'; progressEl.innerHTML = '
' + '
' + '
'; // 优先挂到三色按钮容器所在行(右侧空白),否则回退底部固定 const $host = document.querySelector('#_remind') || document.querySelector('#_mro_remind'); if ($host) { $host.appendChild(progressEl); } else { progressEl.classList.add('jlc-progress-fixed'); document.body.appendChild(progressEl); } } return progressEl; } window.$progress = { start: (label, total) => { const el = ensureProgressEl(); el.querySelector('.jlc-progress-text').textContent = label || '正在处理'; el.querySelector('.jlc-progress-count').textContent = `0 / ${total}`; el.querySelector('.jlc-progress-fill').style.width = '0%'; el.style.display = ''; }, update: (current, total) => { if (!progressEl) return; const pct = total > 0 ? Math.min(100, Math.round(current / total * 100)) : 0; progressEl.querySelector('.jlc-progress-count').textContent = `${current} / ${total}`; progressEl.querySelector('.jlc-progress-fill').style.width = pct + '%'; }, finish: () => { if (!progressEl) return; if (progressEl.parentNode) { progressEl.parentNode.removeChild(progressEl); } progressEl = null; } }; })(window); (async function() { 'use strict'; // 说明:脚本用 addClass('line-box') 给搜索行打标记、getParentRow 靠这个类找行, // 但样式完全交给站点自身的 CSS。绝不注入 .line-box 相关规则——脚本会给 // 原本没有该类的 section 补上这个类,一旦注入 display:flex 就会覆盖站点的 // 行布局(站点自己用的可能是 grid 或别的排版),造成页面变形。 // jQuery 走 @require,取不到时后面的代码全是空引用,早点退出并说明原因 if (typeof $ === 'undefined') { console.error('[JLC] jQuery 未加载(@require 失败),脚本停止'); return; } /** * 空列表占位组件 * @class EmptyState */ class EmptyState { /** * 构造函数 * @param {string} selector 容器选择器 * @param {object} options 配置选项 */ constructor(selector, options = {}) { // 默认配置 const defaults = { icon: 'fa fa-inbox', // 图标类名(推荐使用Font Awesome) iconSize: 48, // 图标尺寸 title: '暂无数据', // 主标题 description: '', // 描述文本 showAction: false, // 是否显示操作按钮 actionText: '刷新', // 按钮文字 actionClass: 'btn btn-primary', // 按钮样式类 onAction: null // 按钮点击回调 }; // 合并配置 this.settings = $.extend({}, defaults, options); // 容器元素 this.$container = $(selector); if (this.$container.length === 0) { console.error('EmptyState: 容器元素未找到'); return; } // 初始化 this._init(); } /** * 初始化组件 * @private */ _init() { // 创建占位元素 this.$element = $(` `); // 设置图标尺寸 this.$element.find('.empty-state-icon i').css({ 'font-size': `${this.settings.iconSize}px`, 'width': `${this.settings.iconSize}px`, 'height': `${this.settings.iconSize}px` }); // 添加到容器 this.$container.append(this.$element); // 绑定事件 if (this.settings.showAction && this.settings.onAction) { this.$element.find('button').on('click', this.settings.onAction); } // 确保样式存在 this._ensureStyles(); } /** * 确保样式存在 * @private */ _ensureStyles() { if ($('#empty-state-styles').length === 0) { $(' `) // 多选非新人券(品牌数为 0 时提示且不切换) $('.get_notnew_coupon').click(() => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.notNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.notNew))) // 多选品牌新人券 $('.get_brand_new_coupon').click(() => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.brandNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.brandNew))) // 多选商城新人券 $('.get_mall_new_coupon').click(() => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.mallNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.mallNew))) } } /** * 获取优惠券列表信息,并暂存在变量集合中 * 只获取1元购的优惠券 */ async getAllCoupon() { if (Base.allOneCouponMap.size > 0) { return; } const buildData = (jsonText) => { const json = JSON.parse(jsonText); if (json.code === 200) { // 取数据 const resultMap = json.result.couponModelVOListMap; const couponList = Object.values(resultMap).flat(); const couponMaps = CouponHelper.buildBrandCouponMaps(couponList, this.someCouponMapping); Base.allOneCouponMap = couponMaps.allOneCouponMap; Base.brandNewCouponMap = couponMaps.brandNewCouponMap; Base.mallNewCouponMap = couponMaps.mallNewCouponMap; Base.notNewCouponMap = couponMaps.notNewCouponMap; console.log('allOneCouponMap: ', Base.allOneCouponMap); console.log('brandNewCouponMap: ', Base.brandNewCouponMap); console.log('mallNewCouponMap: ', Base.mallNewCouponMap); console.log('notNewCouponMap: ', Base.notNewCouponMap); } } // 获取缓存的我的优惠券数据 const couponData = Util.getSessionData('COUPON_DATA'); if (couponData) { buildData(couponData); return; } if (this.couponLoadingPromise) { return this.couponLoadingPromise; } // http获取优惠券信息 this.couponLoadingPromise = Util.getAjax(`https://activity.szlcsc.com/activity/coupon`) .then(json => { Util.setSessionData('COUPON_DATA', json); buildData(json); }) .finally(() => { this.couponLoadingPromise = null; }); return this.couponLoadingPromise; } /** * 一键搜索淘宝 */ appendSearchTbBtn() { const $cartButtons = $('button:contains("加入购物车")'); const rows = $cartButtons.toArray().map(button => { const $button = $(button); return { button, searchButtonCount: $button.siblings('.searchTaobao_').length }; }); SearchPageDomHelper.collectRowsNeedingSearchTaobaoButton(rows).forEach(({ button }) => { $(button).after(` `); }); /** * 非阻容,其他数据处理 * @param {*} parents 行级标签 * @param {*} resArr 数据存放的数组 */ function other(parents, resArr) { let productName = parents.find('dl dd:eq(0)').text().trim() || ''; if (productName.length === 0 || resArr.length > 0) { return; } let footprint = parents.find('dl:contains("封装") dd span').text().trim() || ''; resArr.push(productName); resArr.push(footprint); } /** * 电阻数据处理 * @param {*} parents 行级标签 * @param {*} resArr 数据存放的数组 */ function R(parents, resArr) { const r = parents.find('dl:contains("阻值") dd span:eq(0)').text().replace('Ω', '').trim() || ''; if (r.length === 0 || resArr.length > 0) { return; } const f = parents.find('dl:contains("封装") dd span:eq(0)').text().trim() || ''; const j = parents.find('dl:contains("精度") dd span:eq(0)').text().replace('±', '').trim() || ''; resArr.push(r); resArr.push(f); resArr.push(j); } /** * 电容数据处理 * @param {*} parents 行级标签 * @param {*} resArr 数据存放的数组 */ function C(parents, resArr) { const c = parents.find('dl:contains("容值") dd span:eq(0)').text().trim() || ''; if (c.length === 0 || resArr.length > 0) { return; } const v = parents.find('dl:contains("额定电压") dd span:eq(0)').text().trim() || ''; const j = parents.find('dl:contains("精度") dd span:eq(0)').text().replace('±', '').trim() || ''; const f = parents.find('dl:contains("封装") dd span:eq(0)').text().trim() || ''; resArr.push(c); resArr.push(v); resArr.push(j); resArr.push(f); } $('.searchTaobao_:not([addedClickHandler])').attr('addedClickHandler', true).on('click', function () { let searchArrVals = []; const $parents = Base.getParentRow(this); // 阻容处理、其他元件处理 R($parents, searchArrVals); C($parents, searchArrVals); other($parents, searchArrVals); GM_openInTab(`https://s.taobao.com/search?q=${searchArrVals.join('/')}`, { active: true, insert: true, setParent: true }) }) } /** * 左侧封装搜索 */ appendLeftRowBtns() { const rows = this.getSearchRows(); [...rows.find('button:contains("复制")')].forEach(row => { const $btn = $(row); const specName = $btn.closest('section').find('dl:contains("封装")').find('dd').text().trim(); if (!$btn.length || !specName) { return; } const hasFuzzyButton = $btn.siblings('.btn_search_manual_fuzzy, button:contains("封装模糊匹配")').length > 0; const hasExactButton = $btn.siblings('.btn_search_manual_exact, button:contains("封装精确匹配")').length > 0; if (!hasFuzzyButton) { $btn.before(``); } if (!hasExactButton) { $btn.before(``); } }); $('.btn_search_manual').off('click').on('click', function (e) { this._clickSpecFunc($(e.currentTarget), $(e.currentTarget).attr('spec-name'), $(e.currentTarget).attr('select-type')); }.bind(this)); } /** * 获取搜索结果行 */ getSearchRows() { return Base.getSearchRows(); } /** * 获取封装筛选行 */ static getPackageFilterRow() { return $('li').filter(function () { const text = $(this).text().replace(/\s+/g, ''); return text.includes('封装') && ( text.includes('多选') || text.includes('全选') || $(this).find('input.ant-checkbox-input').length > 0 ); }).first(); } /** * 获取封装多选面板 */ static getPackageMultiPanel() { const $row = SearchPageHelper.getPackageFilterRow(); const $items = $row.find('li[title]').has('input.ant-checkbox-input'); const $confirm = $row.find('button').filter(function () { return $(this).text().trim() === '确定'; }).first(); const $cancel = $row.find('button').filter(function () { return $(this).text().trim() === '取消'; }).first(); if ($row.length && $items.length && $confirm.length) { return { $row, $items, $confirm, $cancel }; } return null; } /** * 获取封装筛选项标题 */ static collectPackageOptionTitles($items) { return $items.toArray().map(item => $(item).attr('title') || '').filter(Boolean); } /** * 清空当前已选中的封装选项,避免叠加历史选择 */ static clearCheckedPackageOptions($items) { $items.each(function () { const $label = $(this).find('label.ant-checkbox-wrapper').first(); const $input = $label.find('input.ant-checkbox-input').first(); if ($input.length && $input.prop('checked')) { $label.trigger('click'); } }); } /** * 按匹配方式勾选封装选项 */ static selectPackageOption($items, specName, selectType) { const optionTitles = SearchPageHelper.collectPackageOptionTitles($items); const matchedTitle = SearchPackageFilterHelper.resolveMatchTitle(specName, optionTitles, selectType); if (!matchedTitle) { return null; } const $targetItem = $items.filter(function () { return ($(this).attr('title') || '') === matchedTitle; }).first(); if (!$targetItem.length) { return null; } const $label = $targetItem.find('label.ant-checkbox-wrapper').first(); const $input = $label.find('input.ant-checkbox-input').first(); if ($input.length && !$input.prop('checked')) { $label.trigger('click'); } return matchedTitle; } async _clickSpecFunc(that, specName, selectType) { const $row = SearchPageHelper.getPackageFilterRow(); if (!$row.length) { window.$message?.warning('没有找到封装筛选行', 2000); return; } if ($row.find('input.ant-checkbox-input').length === 0) { const $multiBtn = $row.find('div,button,span').filter(function () { return $(this).text().trim() === '多选'; }).last(); if (!$multiBtn.length) { window.$message?.warning('没有找到封装多选入口', 2000); return; } $multiBtn.trigger('click'); } let panel; try { panel = await SearchPageHelper.waitFor( () => SearchPageHelper.getPackageMultiPanel(), 2000 ); } catch (error) { console.warn(error); window.$message?.warning('封装多选面板打开超时,请重试', 2000); return; } const { $items, $confirm, $cancel } = panel; SearchPageHelper.clearCheckedPackageOptions($items); const matchedTitle = SearchPageHelper.selectPackageOption($items, specName, selectType); if (SearchPackageFilterHelper.shouldClosePanelAfterMatch(matchedTitle)) { if ($cancel?.length) { $cancel.trigger('click'); } const matchModeText = selectType === SearchPackageFilterHelper.MATCH_TYPE.fuzzy ? '模糊匹配' : '精确匹配'; window.$message?.warning(`没有找到可${matchModeText}的封装:${specName}`, 2500); return; } await SearchPageHelper.nextFrame(); $confirm.trigger('click'); } }; /** * 搜索页凑单列表 */ class SearchListHelper { // 使用私有静态字段保存单例实例 static instance; // 是否已添加右下角的按钮 static btnStatus = false; // 请求状态 static fetchStatus = false; // 分页大小 static searchPageRealSize = 200; // 查询结果暂存 static listData = []; // 缓存的筛选参数(品牌页) static cachedFilterParams = null; // 缓存的筛选参数(搜索页) static cachedSearchFilterParams = null; // 缓存的筛选参数(分类页) static cachedCatalogFilterParams = null; // 初始化默认选中状态 static defaultTabs = { region: '江苏', userType: "all" }; /** * 初始化请求拦截器,监听品牌页筛选请求 */ static initRequestInterceptor() { const brandTargetUrl = 'list.szlcsc.com/brand/product'; const searchTargetUrl = 'so.szlcsc.com/query/product'; const catalogTargetUrl = 'list.szlcsc.com/parameter'; // 拦截 XMLHttpRequest const originalXhrOpen = XMLHttpRequest.prototype.open; const originalXhrSend = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.open = function(method, url, ...args) { this._url = url; this._method = method; return originalXhrOpen.apply(this, [method, url, ...args]); }; XMLHttpRequest.prototype.send = function(body) { // 品牌页 GET 请求拦截 if (this._url && this._url.includes(brandTargetUrl)) { const urlObj = new URL(this._url, window.location.origin); const params = Object.fromEntries(urlObj.searchParams.entries()); SearchListHelper.cachedFilterParams = params; console.log('[筛选拦截-品牌页] 缓存参数:', params); } // 搜索页 POST 请求拦截 if (this._url && this._url.includes(searchTargetUrl) && this._method?.toUpperCase() === 'POST') { try { const params = typeof body === 'string' ? JSON.parse(body) : body; SearchListHelper.cachedSearchFilterParams = params; console.log('[筛选拦截-搜索页] 缓存参数:', params); } catch (e) { console.warn('[筛选拦截-搜索页] 解析请求体失败:', e); } } // 分类页 POST 请求拦截 if (this._url && this._url.includes(catalogTargetUrl) && this._method?.toUpperCase() === 'POST') { try { const params = typeof body === 'string' ? JSON.parse(body) : body; SearchListHelper.cachedCatalogFilterParams = params; console.log('[筛选拦截-分类页] 缓存参数:', params); } catch (e) { console.warn('[筛选拦截-分类页] 解析请求体失败:', e); } } return originalXhrSend.apply(this, [body]); }; // 拦截 fetch const originalFetch = window.fetch; window.fetch = function(url, options = {}) { const urlStr = typeof url === 'string' ? url : url?.url || ''; // 品牌页 GET 请求拦截 if (urlStr.includes(brandTargetUrl)) { const urlObj = new URL(urlStr, window.location.origin); const params = Object.fromEntries(urlObj.searchParams.entries()); SearchListHelper.cachedFilterParams = params; console.log('[筛选拦截-品牌页] (fetch) 缓存参数:', params); } // 搜索页 POST 请求拦截 if (urlStr.includes(searchTargetUrl) && options.method?.toUpperCase() === 'POST') { try { const body = options.body; const params = typeof body === 'string' ? JSON.parse(body) : body; SearchListHelper.cachedSearchFilterParams = params; console.log('[筛选拦截-搜索页] (fetch) 缓存参数:', params); } catch (e) { console.warn('[筛选拦截-搜索页] 解析请求体失败:', e); } } // 分类页 POST 请求拦截 if (urlStr.includes(catalogTargetUrl) && options.method?.toUpperCase() === 'POST') { try { const body = options.body; const params = typeof body === 'string' ? JSON.parse(body) : body; SearchListHelper.cachedCatalogFilterParams = params; console.log('[筛选拦截-分类页] (fetch) 缓存参数:', params); } catch (e) { console.warn('[筛选拦截-分类页] 解析请求体失败:', e); } } return originalFetch.apply(this, [url, options]); }; console.log('[筛选拦截] 请求拦截器已初始化 (品牌页+搜索页+分类页)'); } constructor() { // 如果实例已存在,直接返回 if (SearchListHelper.instance) { return SearchListHelper.instance; } // 保存当前实例 SearchListHelper.instance = this; // 初始化请求拦截器 setTimeout(() => { SearchListHelper.initRequestInterceptor(); }, 1500); } static async start(brandsNameOrSearchText, brandsId, maxCount, stock, parallel = false, onProgress = null) { SearchListHelper.fetchStatus = false; // 根据页面类型选择不同的数据获取方式 const isSearchPage = location.href.includes('so.szlcsc.com'); const isCatalogPage = location.href.includes('list.szlcsc.com/catalog'); if (isSearchPage) { // 搜索页使用 getSearchProducts 方法 SearchListHelper.listData = await SearchListHelper.getSearchProducts(brandsNameOrSearchText, maxCount, onProgress); } else if (isCatalogPage) { // 分类页使用 getCatalogProducts 方法 // 从URL中提取catalogId,例如 /catalog/381.html -> 381 const catalogMatch = location.href.match(/\/catalog\/(\d+)/); const catalogId = catalogMatch ? catalogMatch[1] : ''; SearchListHelper.listData = await SearchListHelper.getCatalogProducts(catalogId, maxCount, onProgress); } else { // 品牌页使用 getBrandsProducts_new 方法 SearchListHelper.listData = await SearchListHelper.getBrandsProducts_new(brandsNameOrSearchText, brandsId, maxCount, stock, onProgress); } console.log(SearchListHelper.listData); SearchListHelper.setCouponSign(); SearchListHelper.renderMinPriceSearch(); } /** * 获取搜索页商品列表(使用缓存的筛选参数) * @param keyword 搜索关键词 * @param maxCount 最大商品数量 * @param onProgress 进度回调函数 * @returns {Promise} */ static getSearchProducts(keyword, maxCount = null, onProgress = null) { return new Promise((resolve, reject) => { const url = 'https://so.szlcsc.com/query/product'; let products = []; let counts = 0; const getData = (page) => { // 触发进度回调 if (onProgress) { onProgress({ loaded: counts, page: page, status: 'loading' }); } // 默认参数 let data = { "currentPage": page, "pageSize": 30, "catalogIdFilter": "", "brandIdFilter": "", "standardFilter": "", "arrangeFilter": "", "labelFilter": "", "authenticationFilter": "", "keyword": keyword, "sortNumber": 0, "satisfyStockType": "", "startPrice": "", "endPrice": "", "demandNumber": "", "spotFilter": 1, "discountFilter": 1, "hasDataFile": false, "brandPlaceFilter": "", "secondKeyword": "", "queryParameterValue": "", "lastParamName": "" }; // 如果有缓存的筛选参数,合并到请求参数中 if (SearchListHelper.cachedSearchFilterParams) { const cached = SearchListHelper.cachedSearchFilterParams; data = { ...data, catalogIdFilter: cached.catalogIdFilter || "", brandIdFilter: cached.brandIdFilter || "", standardFilter: cached.standardFilter || "", arrangeFilter: cached.arrangeFilter || "", labelFilter: cached.labelFilter || "", authenticationFilter: cached.authenticationFilter || "", brandPlaceFilter: cached.brandPlaceFilter || "", startPrice: cached.startPrice || "", endPrice: cached.endPrice || "", queryParameterValue: cached.queryParameterValue || "", lastParamName: cached.lastParamName || "" }; console.log('[筛选同步-搜索页] 使用缓存的筛选参数:', data); } Util.postAjaxJSON(url, data).then(res => { if (!res) return reject('获取搜索商品列表失败'); res = typeof res === 'object' ? res : JSON.parse(res); if (!res.code || res.code !== 200) return reject(res.msg || '获取搜索商品列表失败'); const list = res?.result?.searchResult?.productRecordList; if (!list || list.length === 0) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } products = products.concat(list); counts += list.length; if (maxCount && counts >= maxCount) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } getData(page + 1); }).catch(err => { reject(err); }); }; getData(1); }); } /** * 获取分类页商品列表(使用缓存的筛选参数) * @param catalogId 分类ID * @param maxCount 最大商品数量 * @param onProgress 进度回调函数 * @returns {Promise} */ static getCatalogProducts(catalogId, maxCount = null, onProgress = null) { return new Promise((resolve, reject) => { const url = 'https://list.szlcsc.com/category/product'; let products = []; let counts = 0; const getData = (page) => { // 触发进度回调 if (onProgress) { onProgress({ loaded: counts, page: page, status: 'loading' }); } // 默认参数 let data = { "currentPage": page, "pageSize": 30, "catalogIdFilter": catalogId || "", "brandIdFilter": "", "standardFilter": "", "brandPlaceFilter": "", "brandOriginFilter": "", "labelFilter": "", "arrangeFilter": "", "smtLabelFilter": "", "spotFilter": 1, "discountFilter": 1, "startPrice": "", "endPrice": "", "sortNumber": 0, "queryParameterValue": "", "lastParamName": "", "keyword": "", "secondKeyword": "", "hasDataFile": false, "demandNumber": "", "satisfyStockType": "", "queryProductTypeCode": "", "authenticationFilter": "" }; // 如果有缓存的筛选参数,合并到请求参数中 if (SearchListHelper.cachedCatalogFilterParams) { const cached = SearchListHelper.cachedCatalogFilterParams; data = { ...data, catalogIdFilter: cached.catalogIdFilter || catalogId || "", brandIdFilter: cached.brandIdFilter || "", standardFilter: cached.standardFilter || "", brandPlaceFilter: cached.brandPlaceFilter || "", brandOriginFilter: cached.brandOriginFilter || "", labelFilter: cached.labelFilter || "", arrangeFilter: cached.arrangeFilter || "", smtLabelFilter: cached.smtLabelFilter || "", startPrice: cached.startPrice || "", endPrice: cached.endPrice || "", queryParameterValue: cached.queryParameterValue || "", lastParamName: cached.lastParamName || "", authenticationFilter: cached.authenticationFilter || "" }; console.log('[筛选同步-分类页] 使用缓存的筛选参数:', data); } Util.postAjaxJSON(url, data).then(res => { if (!res) return reject('获取分类商品列表失败'); res = typeof res === 'object' ? res : JSON.parse(res); if (!res.code || res.code !== 200) return reject(res.msg || '获取分类商品列表失败'); const list = res?.result?.searchResult?.productRecordList; if (!list || list.length === 0) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } products = products.concat(list); counts += list.length; if (maxCount && counts >= maxCount) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } getData(page + 1); }).catch(err => { reject(err); }); }; getData(1); }); } // 设置商品列表的券标记 static setCouponSign() { SearchListHelper.listData.forEach(e => { const brandName = Util.brandNameProcess(e.lightBrandName || ''); const coupon = Base.allOneCouponMap.get(brandName); if (coupon) { e.couponCategory = coupon.couponCategory; } }) } // 渲染页面 async renderListItems(onProgress = null) { const stock = 'js'; const searchValue = $('#global-seach-input').val() || ''; let brandId = null; if (location.pathname.indexOf('brand') >= 0) { brandId = /\d+/.exec(location.pathname)[0] || null; } await SearchListHelper.start(searchValue, brandId, 300, stock, false, onProgress); } render() { if (!this.btnStatus) { $('head').prepend(``); $('body').prepend(`
`); // 使用 jQuery 为按钮绑定点击事件 const self = this; $('#searchListButton').on('click', async function() { const $btn = $(this); const isShow = $btn.attr('show') !== 'true'; $btn.attr('show', isShow); if (isShow) { $('#cardContainer').show(); // 初始化带加载动画的空状态 const emptyState = new EmptyState('#listContainer', { icon: 'loading-spinner', // 使用加载动画 title: '正在加载数据...', description: '请稍候,正在获取商品列表' }); emptyState.show(); // 进度回调函数 const onProgress = (progress) => { if (progress.status === 'loading') { emptyState.update({ title: `正在加载第 ${progress.page} 页...`, description: `已加载 ${progress.loaded} 条商品数据` }); } else if (progress.status === 'done') { emptyState.update({ title: '加载完成', description: `共加载 ${progress.loaded} 条商品数据` }); } }; try { await self.renderListItems(onProgress); } finally { emptyState.hide(); emptyState.destroy(); } } else { $('#cardContainer').hide(); } }); // 点击 Tab 按钮 $('.tab-button').on('click', function () { const $button = $(this); const group = $button.data('group'); // 获取 data-group 属性 const value = $button.data('value'); // 获取 data-value 属性 // 移除同组所有按钮的 active 类 $('.tab-button').filter(function () { return $(this).data('group') === group; }).removeClass('active'); // 为当前按钮添加 active 类 $button.addClass('active'); // 更新选中状态 SearchListHelper.defaultTabs[group] = value; console.log('当前选中:', SearchListHelper.defaultTabs); SearchListHelper.renderMinPriceSearch(); }); this.btnStatus = true; } } /** * 搜索主页的凑单逻辑 */ async renderMainPageMinPriceSearch() { // 避免重复执行 if (this.globalSearchEnd) return; const searchInput = $('#search-input'); const searchValue = searchInput.val(); // 输入为空时清空缓存并返回 if (!searchValue?.trim()) { searchTempList = []; return; } this.globalSearchEnd = true; try { // 获取总页数 const totalPage = searchTotalPage(); // 收集表单数据 const formData = Array.from($('form#allProjectFrom > input[type="hidden"]')) .filter(item => !$(item).attr('id')?.includes('SloganVal') && !$(item).attr('id')?.includes('LinkUrlVal')) .reduce((acc, item) => { const name = $(item).attr('name'); acc[name] = $(item).val(); return acc; }, {}); // 创建并发请求队列(限制并发数为3) const requestQueue = []; for (let pn = 1; pn <= totalPage && pn <= 30; pn++) { const data = { ...formData, pageNumber: pn, k: searchValue, sk: searchValue, localQueryKeyword: '' }; requestQueue.push( $.ajax({ url: "https://so.szlcsc.com/search", method: "POST", data: data, timeout: 10000 // 添加超时限制 }) ); } // 显示加载进度 const progressContainer = $('.wait-h2'); progressContainer.html(`数据加载中...
(共${Math.min(totalPage, 30)}页,正在加载第1页...`); // 并发执行请求并跟踪进度 const results = await allWithProgress(requestQueue, ({total, cur}) => { progressContainer.html(`数据加载中...
(共${total}页,正在加载第${cur}页... ${Math.round((cur / total) * 100)}%)`); }); // 处理响应数据(过滤无效响应) const validResults = results.filter( res => res?.code === 200 && res.result?.productRecordList?.length > 0 ); // 合并搜索结果(使用Set去重) searchTempList = [...new Set([ ...searchTempList, ...validResults.flatMap(res => res.result.productRecordList) ])]; // 渲染结果 renderMinPriceSearch(); // 延迟触发筛选事件(使用MutationObserver替代setTimeout) const observer = new MutationObserver(() => { $('#js-filter-btn').trigger('click'); observer.disconnect(); }); observer.observe(document.body, {childList: true, subtree: true}); console.timeEnd('搜索首页凑单渲染速度'); } catch (error) { console.error('搜索请求失败:', error); $('.wait-h2').html('搜索加载失败,请重试'); this.globalSearchEnd = false; } } /** * 搜索页-查找最低价 列表渲染方法 */ static renderMinPriceSearch() { // 修复不同接口productPriceList的层级关系 SearchListHelper.listData.forEach(item => { // 1. 安全地将 item 的 productVO 属性作为回退源 // 如果 item.productVO 不存在,则使用空对象 {} const fallbackVO = item.productVO || {}; // 2. 将 item 的属性(排除 productVO 自身)与 fallbackVO 合并。 // 此步骤是关键: // - {...fallbackVO} 提供 productVO 中的所有值作为默认值。 // - {...item} 覆盖 productVO 中与 item 重名的值,确保 item 自身的值是高优先级的。 const { productVO, ...itemProps } = item; // 暂时排除 productVO 属性 const finalSource = { ...fallbackVO, // 优先级低:提供来自 productVO 的回退值 ...itemProps // 优先级高:覆盖所有来自 item 的值 }; // 3. 从最终合并的 finalSource 对象中解构所有变量 // 现在解构出来的变量,如果 item 中有,就是 item 的值;如果 item 中没有,就是 item.productVO 中的值。 Object.assign(item, finalSource); }); // 如果广东仓和江苏仓同时没有货的话,那么就属于订货商品,不需要显示 // 如果没有价格区间,证明是停售商品 var newList = SearchListHelper.listData.filter(item => !(parseInt(item.jsWarehouseStockNumber || 0) <= 0 && parseInt(item.gdWarehouseStockNumber || 0) <= 0) && item.productPriceList.length > 0); // 去重 const map = new Map(); newList.forEach(item => { map.set(item.productId, item); }); newList = [...map.values()]; // 列表自动正序,方便凑单 newList.sort((o1, o2) => { return (o1.theRatio * o1.productPriceList[0].productPrice * (o1.listProductDiscount || 10) / 10).toFixed(6) - (o2.theRatio * o2.productPriceList[0].productPrice * (o2.listProductDiscount || 10) / 10).toFixed(6); }); // 指定仓库 const {region, userType} = SearchListHelper.defaultTabs; newList.forEach(e => { if (userType === 'all' && region === '江苏') { e.show = (e.jsWarehouseStockNumber > 0); return } else if (userType === 'all' && region === '广东') { e.show = (e.gdWarehouseStockNumber > 0); return } if (region === '江苏') { e.show = (e.jsWarehouseStockNumber > 0) && e.couponCategory === userType; return } else if (region == '广东') { e.show = (e.gdWarehouseStockNumber > 0) && e.couponCategory === userType; return } }) // 取指定条数的数据。默认50个 const html = newList.slice(0, (SearchListHelper.searchPageRealSize || 50)).map(item => { const { productId, lightStandard, lightProductCode, productCode, productMinEncapsulationNumber, productMinEncapsulationUnit, productName, productModel, lightProductModel, productGradePlateId, productPriceList, priceDiscount, listProductDiscount, productGradePlateName, hkConvesionRatio, convesionRatio, theRatio, smtStockNumber, smtLabel, productStockStatus, isPlusDiscount, productUnit, isPresent, isGuidePrice, minBuyNumber, hasSampleRule, breviaryImageUrl, luceneBreviaryImageUrls, productType, productTypeCode, pdfDESProductId, gdWarehouseStockNumber, jsWarehouseStockNumber, paramLinkedMap, recentlySalesCount, batchStockLimit, couponCategory, show, } = item; return `
    ${Object.keys(paramLinkedMap).map(key => { return `
  • ${key}: ${paramLinkedMap[key]}
  • ` }).join('')}
    ${listProductDiscount != null && listProductDiscount < 10 ? `
  • ${listProductDiscount}折
    • ${productPriceList.map(item => { return `
    • ${item.startPurchasedNumber * theRatio}+: 
    • `; }).join('')}
    • 折后价
    • ${productPriceList.map(item => { return `
    • ¥${parseFloat((item.productPrice * (listProductDiscount || 10) / 10).toFixed(6))}
    • `; }).join('')}
    • 原价
    • ${productPriceList.map(item => { return `
    • ¥${item.productPrice}
    • `; }).join('')}
  • ` : ''}

    最低购入价: ${parseFloat((theRatio * productPriceList[0].productPrice * (listProductDiscount || 10) / 10).toFixed(6))}

    ${productPriceList.map(item => { const discountPrice = parseFloat((item.productPrice * (listProductDiscount || 10) / 10).toFixed(6)); return `
  • ${item.startPurchasedNumber * theRatio}+: 

    ¥${discountPrice}
  • `; }).join('')}
  • 广东仓:${gdWarehouseStockNumber}
    江苏仓:${jsWarehouseStockNumber}
  • 个
  • 个
  • ${productMinEncapsulationNumber}个/${productMinEncapsulationUnit}  总额:¥0
    已优惠0元!
  • 近期成交${recentlySalesCount}单
`; }).join(''); $('#listContainer').html(html); $('.cartnumbers').off('change').on('change', function () { let val = $(this).val(); if (!val) { return ; } const theratio = $(this).data("theratio"); val = Math.max(parseInt(val / theratio) * theratio, theratio); $(this).val(val); const productPriceList = $(this).data("productpricelist"); const priceDiscount = $(this).data("pricediscount"); const result = PriceCalculator.calculatePrice(val, theratio, productPriceList, priceDiscount); console.log(val) console.log('计算结果:', result); Base.getParentRow(this).find('.totalPrice').text('¥' + result.discountTotalPrice.toFixed(2)); }); $('.addCartBtn').off('click').on('click', function () { let num = [...Base.getParentRowWithFind(this, '.cartnumbers')] .reduce((a,b)=> a + (parseInt($(b).val()) || 0), 0); if (!num) { const newNum = parseInt($(this).data('theratio')); window.$message.error(`数量为空,已为您修正数量为:${newNum}!`, 3000); num = newNum; } Util.postFormAjax(`https://cart.szlcsc.com/cart/quick`, { productCode: $(this).data('productcode'), productNumber: num }).then(e => { if(JSON.parse(e).code === 200) { window.$message.success('加入购物车成功!', 3000); } }); }); } /** * 获取品牌商品列表 * @param brandsNameOrSearchText 品牌名称或者搜索框内容 * @param brandsId 品牌id,可为空,不为空时提高搜索准确率 * @param maxCount 最大商品数量,为空时返回所有商品 * @param stock 仓库,js/gd * @returns {Promise} */ static getBrandsProducts_old(brandsNameOrSearchText, brandsId = null, maxCount = null, stock = 'js') { return new Promise((resolve, reject) => { const url = 'https://so.szlcsc.com/search'; let products = []; let counts = 0; const getData = (page) => { let data = { os: '', dp: '', sb: 1, // 价格从低排序 queryPlaceProduction: '', pn: page, c: '', k: brandsNameOrSearchText, tc: 0, pds: 0, pa: 0, pt: 0, gp: 0, /*品牌id*/ queryProductDiscount: '', st: '', sk: brandsNameOrSearchText, searchSource: '', bp: '', ep: '', bpTemp: '', epTemp: '', stock: stock, needChooseCusType: '', 'link-phone': '', companyName: '', taxpayerIdNum: '', realityName: '', } if (brandsId) { // data.queryProductGradePlateId = brandsId data.gp = brandsId } Util.postFormAjax(url, data).then(res => { if (!res) return reject('获取品牌商品列表失败') res = typeof res === 'object' ? res : JSON.parse(res) if (!res.code || res.code !== 200) return reject(res.msg || '获取品牌商品列表失败') if (!res.result || !res.result.productRecordList || res.result.productRecordList.length === 0) return resolve(products) products = products.concat(res.result.productRecordList) counts += res.result.productRecordList.length if (maxCount && counts >= maxCount) return resolve(products) getData(page + 1) }).catch(err => { reject(err) }) } getData(1); }) } /** * 获取品牌商品列表 * @param brandsName 品牌名称 * @param brandsId 品牌id,可为空,不为空时提高搜索准确率 * @param maxCount 最大商品数量,为空时返回所有商品 * @param stock 仓库,js/gd * @param onProgress 进度回调函数,参数为 {loaded: number, page: number} * @returns {Promise} */ static getBrandsProducts_new(brandsName, brandsId = null, maxCount = null, stock = 'js', onProgress = null) { // sortNumber 10 广东有货排序 // sortNumber 12 江苏有货排序 // sortNumber 6 销量排序 return new Promise((resolve, reject) => { const url = 'https://list.szlcsc.com/brand/product?'; let products = []; let counts = 0; const sortNumber = !brandsId || brandsId.length == 0 ? 0 : (stock == 'js' ? 1 : 2); const getData = (page) => { // 触发进度回调 if (onProgress) { onProgress({ loaded: counts, page: page, status: 'loading' }); } // 默认参数 let data = { "currentPage": page, "pageSize": 30, "catalogIdFilter": "", "brandIdFilter": brandsId + "", "standardFilter": "", "arrangeFilter": "", "labelFilter": "", "keyword": brandsName, "sortNumber": 6, "satisfyStockType": "", "startPrice": "", "endPrice": "", "demandNumber": "", "spotFilter": 1, "discountFilter": 1, "hasDataFile": false, "brandPlaceFilter": "", "secondKeyword": "", "queryParameterValue": "", "lastParamName": "" } // 如果有缓存的筛选参数,合并到请求参数中 if (SearchListHelper.cachedFilterParams) { const cached = SearchListHelper.cachedFilterParams; // 保留缓存中的筛选条件,但覆盖分页参数 data = { ...data, catalogIdFilter: cached.catalogIdFilter || "", standardFilter: cached.standardFilter || "", arrangeFilter: cached.arrangeFilter || "", labelFilter: cached.labelFilter || "", brandPlaceFilter: cached.brandPlaceFilter || "", smtLabelFilter: cached.smtLabelFilter || "", startPrice: cached.startPrice || "", endPrice: cached.endPrice || "", queryParameterValue: cached.queryParameterValue || "", lastParamName: cached.lastParamName || "" }; console.log('[筛选同步] 使用缓存的筛选参数:', data); } Util.getAjax(url + Util.jsonToUrlParam(data)).then(res => { if (!res) return reject('获取品牌商品列表失败') res = typeof res === 'object'? res : JSON.parse(res) if (!res.code || res.code !== 200) return reject(res.msg || '获取品牌商品列表失败') const list = res?.result?.searchResult?.productRecordList; if (!list || list.length === 0) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } products = products.concat(list) counts += list.length if (maxCount && counts >= maxCount) { if (onProgress) onProgress({ loaded: counts, page: page, status: 'done' }); return resolve(products); } getData(page + 1) }).catch(err => { reject(err) }) } getData(1) }) } /** * 获取品牌商品列表(支持并行或单线程) * @param brandsNameOrSearchText 品牌名称或者搜索框内容 * @param brandsId 品牌id,可为空,不为空时提高搜索准确率 * @param maxCount 最大商品数量,为空时返回所有商品 * @param stock 仓库,js/gd * @param parallel 是否并行执行请求,默认为false(单线程) * @returns {Promise} */ static getBrandsProducts(brandsNameOrSearchText, brandsId = null, maxCount = null, stock = 'js', parallel = false) { return new Promise((resolve, reject) => { const url = 'https://so.szlcsc.com/search'; let products = []; let counts = 0; const getPageDataByNewApi = (page) => { let data = { currentPage: 1, pageSize: 30, catalogIdFilter:526, brandIdFilter:15352, standardFilter: '', brandPlaceFilter: '', labelFilter: '', arrangeFilter: '', smtLabelFilter: '', spotFilter:1, discountFilter: 1, startPrice: '', endPrice: '', sortNumber: 0, queryParameterValue: '', lastParamName: '', keyword: '', secondKeyword: '', hasDataFile:false, demandNumber: '', satisfyStockType: '' } } // 获取单页数据 const getPageData = (page) => { let data = { os: '', dp: '', sb: 1, queryPlaceProduction: '', pn: page, c: '', k: brandsNameOrSearchText, tc: 0, pds: 0, pa: 0, pt: 0, gp: 0, /*品牌id*/ queryProductDiscount: '', st: '', sk: brandsNameOrSearchText, searchSource: '', bp: '', ep: '', bpTemp: '', epTemp: '', stock: stock, needChooseCusType: '', 'link-phone': '', companyName: '', taxpayerIdNum: '', realityName: '', }; if (brandsId) { // data.queryProductGradePlateId = brandsId; data.gp = brandsId; } return Util.postFormAjax(url, data) .then(res => { if (!res) throw new Error('获取品牌商品列表失败'); res = typeof res === 'object' ? res : JSON.parse(res); if (!res.code || res.code !== 200) throw new Error(res.msg || '获取品牌商品列表失败'); return res.result.productRecordList || []; }); }; // 单线程模式(顺序执行) const executeSequentially = (page) => { getPageData(page) .then(pageProducts => { if (pageProducts.length === 0) return resolve(products); products = products.concat(pageProducts); counts += pageProducts.length; if (maxCount && counts >= maxCount) { return resolve(products.slice(0, maxCount)); } executeSequentially(page + 1); }) .catch(err => reject(err)); }; // 并行模式(不考虑顺序) const executeInParallel = () => { // 先获取第一页,确定总页数 getPageData(1) .then(firstPageProducts => { if (firstPageProducts.length === 0) return resolve([]); // 假设每页数量相同,计算总页数 const estimatedTotalPages = maxCount ? Math.ceil(maxCount / firstPageProducts.length) : 10; // 默认最多10页(防止无限请求) // 生成所有页面的请求数组 const pageRequests = []; for (let i = 1; i <= estimatedTotalPages; i++) { pageRequests.push(getPageData(i)); } // 并行执行所有请求 Promise.all(pageRequests) .then(allPages => { const allProducts = allPages.flat(); if (maxCount) { resolve(allProducts.slice(0, maxCount)); } else { resolve(allProducts); } }) .catch(err => reject(err)); }) .catch(err => reject(err)); }; // 根据 parallel 参数选择执行模式 if (parallel) { executeInParallel(); } else { executeSequentially(1); } }); } } // 分类品牌颜色定时器开启状态,默认false let catalogBrandColorTaskIsStartStatus = false; let catalogBrandColorObserver = null; let searchPageDomObserver = null; let searchPageRuntimeStarted = false; let activeSearchPageUrl = ''; // 防抖函数 function debounce(fn, delay) { let timer = null; return function (...args) { if (timer) clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), delay); }; } function disconnectSearchPageObservers() { if (catalogBrandColorObserver) { catalogBrandColorObserver.disconnect(); catalogBrandColorObserver = null; } if (searchPageDomObserver) { searchPageDomObserver.disconnect(); searchPageDomObserver = null; } MroPageHelper.disconnectObservers(); catalogBrandColorTaskIsStartStatus = false; searchPageRuntimeStarted = false; activeSearchPageUrl = ''; } // ======================================================== // MRO 页面(list.szlcsc.com/mro/**)增强 // 券数据与元器件页共用,DOM 交互完全独立: // 品牌筛选行是 li>div>h2 + ul>li[title],多选面板是 Radix checkbox + 取消/确定 // ======================================================== class MroPageHelper { static instance; static colorObserver = null; static domObserver = null; constructor() { if (MroPageHelper.instance) { return MroPageHelper.instance; } this.filterInFlight = false; this.colorReported = false; this.sortCategory = ''; MroPageHelper.instance = this; } static isMroPage(url) { return MroPageRuntimeHelper.isMroPage(url); } /** * 筛选分组行:li > div > h2(品牌|类目|封装) */ static getFilterGroupRow(groupName) { const target = String(groupName || '').replace(/\s+/g, ''); let $matched = $(); $('h2').each(function () { if ($(this).text().replace(/\s+/g, '') !== target) { return; } const $row = $(this).closest('li'); if ($row.length) { $matched = $row.first(); return false; } }); return $matched; } /** * 「多选」入口:叶子节点且文本恰好是多选 */ static getMultiToggle(scope) { const $scope = scope && scope.length ? scope : $(document); return $scope.find('div,button,span').filter(function () { const $el = $(this); return $el.children().length === 0 && $el.text().trim() === '多选'; }).last(); } static getBrandRow() { const $row = MroPageHelper.getFilterGroupRow('品牌'); if ($row.length) { return $row; } // 兜底:从「多选」入口反推所在的分组行 const $toggle = MroPageHelper.getMultiToggle(); return $toggle.length ? $toggle.closest('li').first() : $(); } /** * 商品卡片:div[data-index],且带「加入购物车」按钮 * 注意 .product-group-leader 只是每 5 个里第一个卡片的附加类名,不是外层容器 */ static getCardNodes() { return $('div[data-index]').filter(function () { return $(this).find('button').filter(function () { return $(this).text().trim() === '加入购物车'; }).length > 0; }); } /** * 需要上色的品牌节点: * 1. 品牌筛选行里的 li[title] * 2. 商品卡片的「品牌」dl 里的 span[title](商品名/型号的 title 不动,避免误伤) */ static getBrandTitleNodes() { const nodes = []; const $row = MroPageHelper.getBrandRow(); if ($row.length) { $row.find('li[title]').each(function () { nodes.push(this); }); } $('div[data-index]').each(function () { const $dl = $(this).find('dl'); if (!$dl.length) { return; } $dl.each(function () { const $item = $(this); if ($item.children('dt').first().text().trim() !== '品牌') { return; } $item.find('dd span[title]').each(function () { nodes.push(this); }); }); }); return $(nodes); } /** * 品牌上色(三色) */ colorBrands() { SearchPageHelper.ensureChipTipStyle(); SearchPageHelper.maybeScanPageCouponCounts('mro'); SearchPageHelper.updateCouponButtonCounts(); if (!MroPageRuntimeHelper.shouldColorBrands(Base.allOneCouponMap.size)) { return; } const $nodes = MroPageHelper.getBrandTitleNodes().not('[data-mro-brand-colored]'); if ($nodes.length === 0) { return; } let matchedCount = 0; $nodes.each(function () { const $node = $(this); const originTitle = $node.attr('data-mro-brand-origin') || MroPageRuntimeHelper.normalizeBrandTitle($node.attr('title') || $node.text()); $node.attr('data-mro-brand-colored', 'true'); if (!originTitle) { return; } $node.attr('data-mro-brand-origin', originTitle); const coupon = CouponHelper.findCouponByBrandTitle(originTitle, Base.allOneCouponMap); if (!coupon) { return; } matchedCount++; $node .css('background-color', CouponHelper.getCategoryColor(coupon.couponCategory)) .addClass(CouponHelper.getCategoryClassName(coupon.couponCategory)) .addClass('jlc-brand-colored') .attr('title', `${originTitle}(${CouponHelper.getCategoryLabel(coupon.couponCategory)})`); }); if (matchedCount > 0 && !this.colorReported) { this.colorReported = true; console.log(`[MRO] 品牌上色:本轮命中 ${matchedCount} 个节点,券库品牌数 ${Base.allOneCouponMap.size}`); } } /** * 三色筛选按钮,挂在品牌筛选行下方 */ renderFilterButtons() { if ($('#_mro_remind').length > 0) { return; } const $row = MroPageHelper.getBrandRow(); if (!$row.length) { if (!MroPageHelper.filterRowWarned) { MroPageHelper.filterRowWarned = true; console.warn('[MRO] 没找到品牌筛选行,三色按钮暂未注入(DOM 就绪后会自动补)'); } return; } $row.append(`

非新人

品牌新人

商城新人
点击自动勾选该券类型的品牌
`); $('.mro_get_notnew_coupon').on('click', () => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.notNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.notNew))); $('.mro_get_brand_new_coupon').on('click', () => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.brandNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.brandNew))); $('.mro_get_mall_new_coupon').on('click', () => SearchPageHelper.runCouponCategoryFilter( CouponHelper.CATEGORY.mallNew, () => this.multiFilterBrand(CouponHelper.CATEGORY.mallNew))); } /** * 多选面板的作用域:品牌筛选行内 + 独立滚动面板 * 不能全页扫 checkbox,否则顶部「国产品牌/国际品牌」等快捷勾选会被当成品牌项 */ static getOptionScope() { const $row = MroPageHelper.getBrandRow(); const $scrollPanel = $('ul.so-filter-condition-scroll'); return $row.add($scrollPanel); } /** * 收集多选面板里的品牌选项(Radix checkbox) */ static collectBrandOptions() { const seen = new Map(); MroPageHelper.getOptionScope().find('button[role="checkbox"], input[type="checkbox"]').each(function () { const $checkbox = $(this); const title = MroPageHelper.resolveOptionTitle($checkbox); if (!title || seen.has(title)) { return; } seen.set(title, { title, $checkbox, $host: $checkbox.closest('li'), }); }); return [...seen.values()]; } static resolveOptionTitle($checkbox) { const $host = $checkbox.closest('li'); const titleAttr = MroPageRuntimeHelper.normalizeBrandTitle($host.attr('title') || ''); if (titleAttr) { return titleAttr; } const $label = $checkbox.nextAll('label').first(); if ($label.length) { const labelText = MroPageRuntimeHelper.normalizeBrandTitle($label.text()); if (labelText) { return labelText; } } // 候选行里没有 title 时退回文本,但限制长度,避免把整块筛选面板当成一个选项 const hostText = MroPageRuntimeHelper.normalizeBrandTitle($host.text()); return hostText && hostText.length <= 40 ? hostText : ''; } static isOptionChecked($checkbox) { if (!$checkbox || $checkbox.length === 0) { return false; } const $el = $checkbox.first(); return $el.attr('data-state') === 'checked' || $el.attr('aria-checked') === 'true' || $el.prop('checked') === true; } static clickOption($checkbox) { const el = $checkbox && $checkbox[0]; if (!el) { return; } el.click(); } /** * 多选面板里如果还有「展开」,点一下拿全量品牌 */ static expandIfNeeded(scope) { const $scope = scope && scope.length ? scope : $(document); const $toggle = $scope.find('div,span,button').filter(function () { const $el = $(this); return $el.children().length === 0 && $el.text().trim() === '展开'; }).last(); if (!$toggle.length) { return false; } $toggle[0].click(); return true; } static getConfirmButton() { const $buttons = $('button').filter(function () { return $(this).text().trim() === '确定'; }); const $visible = $buttons.filter(function () { return $(this).is(':visible'); }); if ($visible.length) { return $visible.last(); } // 面板动画/隐藏样式会让 :visible 判不出来,此时只接受唯一的「确定」,避免误点其他弹窗 return $buttons.length === 1 ? $buttons : $(); } /** * 按券类型一键多选品牌 * 只勾选命中的品牌(与元器件页行为一致),不取消用户已勾选的项 */ async multiFilterBrand(couponCategory) { if (this.filterInFlight) { return; } this.filterInFlight = true; try { await new SearchPageHelper().getAllCoupon(); if (!Base.allOneCouponMap.size) { window.$message?.warning('券数据为空,先刷新页面再试', 2500); return; } const $row = MroPageHelper.getBrandRow(); if (!$row.length) { window.$message?.warning('没有找到品牌筛选行', 2500); return; } let $multiToggle = MroPageHelper.getMultiToggle($row); let clearedSelection = false; if (!$multiToggle.length) { // 已选状态下「多选」消失只剩「清除」→ 先清除恢复未选态,等入口恢复 const { toggle, cleared } = await SearchPageHelper.ensureBrandMultiToggle({ getRow: () => MroPageHelper.getBrandRow(), findToggle: scope => MroPageHelper.getMultiToggle(scope), }); $multiToggle = toggle; clearedSelection = cleared; } if (!$multiToggle.length) { window.$message?.warning('没有找到品牌多选入口', 2500); return; } if (MroPageHelper.collectBrandOptions().length === 0) { $multiToggle[0].click(); } let options; try { options = await SearchPageHelper.waitFor(() => { const list = MroPageHelper.collectBrandOptions(); return list.length > 0 ? list : null; }, 3000); } catch (error) { console.warn(error); window.$message?.warning('品牌多选面板打开超时,请重试', 2500); return; } if (MroPageHelper.expandIfNeeded()) { await new Promise(resolve => setTimeout(resolve, 300)); options = MroPageHelper.collectBrandOptions(); } // 清除过旧筛选时等站点把品牌列表刷新回全量, // 否则残留列表(上一次券类型的品牌)会被误当全量 if (clearedSelection) { await SearchPageHelper.waitForPanelItems(null, { expectTotal: Base.pageCouponScanTotal, timeout: 6000, collect: () => MroPageHelper.collectBrandOptions(), }); options = MroPageHelper.collectBrandOptions(); } const matchTargets = list => list.filter(option => { const coupon = CouponHelper.findCouponByBrandTitle(option.title, Base.allOneCouponMap); return MroPageRuntimeHelper.isSameCouponCategory(coupon, couponCategory); }); let targets = matchTargets(options); if (targets.length === 0 && (Base.pageCouponCounts?.[couponCategory] || 0) > 0) { // 按钮数字说有该券类型的品牌,面板里却一个都没有:等列表刷新后重试 console.warn('[JLC] MRO 面板选项数与扫描缓存不符,等待品牌列表刷新后重试'); await SearchPageHelper.waitForPanelItems(null, { expectTotal: Base.pageCouponScanTotal, timeout: 4000, collect: () => MroPageHelper.collectBrandOptions(), }); targets = matchTargets(MroPageHelper.collectBrandOptions()); } if (targets.length === 0) { // 没有对应券品牌:自动收起多选面板,别让它空着停在那 const $toggleToClose = MroPageHelper.getMultiToggle($row); if ($toggleToClose.length) { $toggleToClose[0].click(); } window.$message?.warning( `当前品牌列表里没有${CouponHelper.getCategoryLabel(couponCategory)}品牌(共 ${options.length} 个品牌),已收起面板`, 3000 ); return; } // 目标较多时显示进度条(MRO 是同步勾选,进度会很快走完) const showProgress = targets.length >= 5; if (showProgress) { window.$progress?.start( `正在勾选${CouponHelper.getCategoryLabel(couponCategory)}品牌`, targets.length ); } let mroProcessed = 0; targets.forEach(option => { if (!MroPageHelper.isOptionChecked(option.$checkbox)) { MroPageHelper.clickOption(option.$checkbox); } mroProcessed++; if (showProgress) window.$progress?.update(mroProcessed, targets.length); }); await SearchPageHelper.nextFrame(); await SearchPageHelper.nextFrame(); const $confirm = MroPageHelper.getConfirmButton(); if (!$confirm.length) { window.$message?.warning('没有找到「确定」按钮,请手动确认', 2500); return; } $confirm[0].click(); window.$message?.success( `已勾选 ${targets.length} 个${CouponHelper.getCategoryLabel(couponCategory)}品牌`, 2500 ); } finally { window.$progress?.finish(); this.filterInFlight = false; } } /** * 卡片字段读取:dl > dt(品牌|型号) + dd span[title] */ static readCardField($card, fieldName) { let value = ''; $card.find('dl').each(function () { if (value) { return; } const $dl = $(this); if ($dl.children('dt').first().text().trim() !== fieldName) { return; } const $value = $dl.find('dd span[title]').first(); const rawValue = $value.attr('title') || $dl.find('dd').text() || ''; // 上色会把「(品牌新人券)」写进 title,取值时还原成原始品牌名 value = $value.attr('data-mro-brand-origin') || MroPageRuntimeHelper.normalizeBrandTitle(rawValue); }); return value; } /** * 当前页所有商品卡片 */ static collectCards() { const cards = []; MroPageHelper.getCardNodes().each(function () { const $card = $(this); const brand = MroPageHelper.readCardField($card, '品牌'); const model = MroPageHelper.readCardField($card, '型号'); const priceText = $card.find('li').filter(function () { return $(this).text().includes('¥'); }).first().text(); const price = MroPageRuntimeHelper.parsePrice(priceText); const href = $card.find('a[aria-label="点击跳转详情"]').attr('href') || $card.find('a[href*="item.szlcsc.com"]').first().attr('href') || ''; const coupon = brand ? CouponHelper.findCouponByBrandTitle(brand, Base.allOneCouponMap) : null; if (!brand && !model) { return; } cards.push({ brand, model, price: Number.isFinite(price) ? price : '', href, coupon, category: coupon ? coupon.couponCategory : '', }); }); return cards; } /** * 一键搜淘宝(品牌 + 型号) */ appendTaobaoButtons() { MroPageHelper.getCardNodes().each(function () { const $card = $(this); const $cartButton = $card.find('button').filter(function () { return $(this).text().trim() === '加入购物车'; }).first(); if (!$cartButton.length) { return; } const $actionRow = $cartButton.closest('div.flex.items-center.justify-between'); if (!$actionRow.length || $card.find('.mro_search_taobao').length > 0) { return; } $actionRow.after(` `); }); $('.mro_search_taobao:not([data-mro-bound])').attr('data-mro-bound', 'true').on('click', function (event) { event.preventDefault(); event.stopPropagation(); const $card = $(this).closest('div[data-index]'); const brand = MroPageHelper.readCardField($card, '品牌'); const model = MroPageHelper.readCardField($card, '型号'); const keyword = MroPageRuntimeHelper.buildTaobaoKeyword(brand, model); if (!keyword) { window.$message?.warning('没有取到品牌/型号,无法搜索', 2000); return; } GM_openInTab(`https://s.taobao.com/search?q=${encodeURIComponent(keyword)}`, { active: true, insert: true, setParent: true }); }); } /** * 右下角价格排序面板(数据来自当前页 DOM,不依赖 MRO 接口) */ renderPriceSorter() { if ($('#mroSortButton').length > 0) { return; } $('body').append(`
点「价格排序」加载当前页商品
`); $('#mroSortButton').on('click', () => { const $panel = $('#mroSortPanel'); $panel.toggleClass('open'); if ($panel.hasClass('open')) { MroPageHelper.renderSortList(this.sortCategory); } }); $('#mroSortClose').on('click', () => $('#mroSortPanel').removeClass('open')); $('.mro-sort-tab').on('click', event => { const $tab = $(event.currentTarget); $('.mro-sort-tab').removeClass('active'); $tab.addClass('active'); this.sortCategory = $tab.attr('data-category') || ''; MroPageHelper.renderSortList(this.sortCategory); }); $('#mroSortPanel').on('click', '.mro-sort-row', function () { const href = $(this).attr('data-href'); if (!href) { return; } GM_openInTab(href, { active: true, insert: true, setParent: true }); }); } static renderSortList(category = '') { const $body = $('#mroSortPanel .mro-sort-body'); if (!$body.length) { return; } const cards = MroPageRuntimeHelper.filterCardsByCategory(MroPageHelper.collectCards(), category); const sorted = MroPageRuntimeHelper.sortByPrice(cards); const { escapeHtml } = MroPageRuntimeHelper; $('#mroSortPanel .mro-sort-count').text(`当前页 ${sorted.length} 件`); if (sorted.length === 0) { $body.html('
当前页没有匹配的商品(滚动加载后会更新)
'); return; } $body.html(sorted.map(card => { const priceText = card.price === '' ? '—' : `¥${card.price}`; const couponText = card.coupon ? (Number(card.coupon.pay) === 1 ? `1元购·满${escapeHtml(card.coupon.minOrderMoney)}` : `减${escapeHtml(card.coupon.couponPrice)}`) : ''; return `
${escapeHtml(card.brand || '—')} ${escapeHtml(card.model || '—')} ${escapeHtml(priceText)} ${couponText}
`; }).join('')); } static bootstrap() { const helper = new MroPageHelper(); helper.renderFilterButtons(); helper.appendTaobaoButtons(); helper.renderPriceSorter(); SearchPageHelper.bindBrandChipClicks(); SearchPageHelper.decorateSelectedChips(); new SearchPageHelper().getAllCoupon() .then(() => helper.colorBrands()) .catch(error => console.warn('[MRO] 券数据获取失败', error)); if (!MroPageHelper.colorObserver) { const debouncedColor = debounce(() => helper.colorBrands(), 500); MroPageHelper.colorObserver = new MutationObserver(mutations => { if (SearchPageRuntimeHelper.hasNewDomNodes(mutations)) { debouncedColor(); } }); MroPageHelper.colorObserver.observe(document.body, { childList: true, subtree: true }); } if (!MroPageHelper.domObserver) { const debouncedEnhance = debounce(() => { helper.renderFilterButtons(); helper.appendTaobaoButtons(); SearchPageHelper.bindBrandChipClicks(); SearchPageHelper.decorateSelectedChips(); }, 300); MroPageHelper.domObserver = new MutationObserver(mutations => { if (SearchPageRuntimeHelper.hasNewDomNodes(mutations)) { debouncedEnhance(); } }); MroPageHelper.domObserver.observe(document.body, { childList: true, subtree: true }); } console.log('[MRO] 页面增强已启动', { url: location.href, cards: MroPageHelper.getCardNodes().length, brandRow: MroPageHelper.getBrandRow().length > 0, }); } static disconnectObservers() { if (MroPageHelper.colorObserver) { MroPageHelper.colorObserver.disconnect(); MroPageHelper.colorObserver = null; } if (MroPageHelper.domObserver) { MroPageHelper.domObserver.disconnect(); MroPageHelper.domObserver = null; } } /** * 从 MRO 页跳到元器件页时清理残留 UI */ static teardown() { MroPageHelper.disconnectObservers(); $('#mroSortButton, #mroSortPanel, #_mro_remind, .mro_search_taobao').remove(); } } // 搜索页启动 function searchStart() { if (MroPageHelper.isMroPage(location.href)) { try { MroPageHelper.bootstrap(); } catch (error) { console.error('[MRO] 初始化失败', error); } searchPageRuntimeStarted = true; activeSearchPageUrl = location.href; return; } // 从 MRO 页切到元器件页时,清掉 MRO 的按钮和监听 MroPageHelper.teardown(); // 启动诊断:页面结构一变,看这行就知道脚本有没有跑、DOM 有没有变 console.log('[JLC] 元器件页增强启动', { url: location.href, sections: $('section').length, antdCheckbox: $('input.ant-checkbox-input').length, brandTitleNodes: $('div[title], li[title], span[title], a.brand-name[title]').length, }); // 每行追加到按钮组 const searchPageHelper = new SearchPageHelper(); searchPageHelper.appendLeftRowBtns(); searchPageHelper.appendSearchTbBtn(); // 优惠券信息获取 searchPageHelper.getAllCoupon().then(() => { SearchPageHelper.catalogBrandColor(); }).catch(error => { console.warn('[JLC] 优惠券数据获取失败,品牌不会上色', error); }); // // 搜索页按钮组渲染 searchPageHelper.btnsRender(); // 已选品牌标签:点一下只看这个品牌 SearchPageHelper.bindBrandChipClicks(); SearchPageHelper.decorateSelectedChips(); // // 使用 MutationObserver 代替 setInterval 进行上色 if (!catalogBrandColorTaskIsStartStatus) { const debouncedColor = debounce(SearchPageHelper.catalogBrandColor, 500); // 先执行一次 SearchPageHelper.catalogBrandColor(); // 监听DOM变化 catalogBrandColorObserver = new MutationObserver((mutations) => { if (SearchPageRuntimeHelper.hasNewDomNodes(mutations)) { debouncedColor(); } }); catalogBrandColorObserver.observe(document.body, { childList: true, subtree: true }); catalogBrandColorTaskIsStartStatus = true; } if (!searchPageDomObserver) { const debouncedEnhance = debounce(() => { searchPageHelper.appendLeftRowBtns(); searchPageHelper.appendSearchTbBtn(); // 筛选面板如果晚于脚本渲染,这里补一次按钮 searchPageHelper.btnsRender(); SearchPageHelper.bindBrandChipClicks(); SearchPageHelper.decorateSelectedChips(); }, 300); searchPageDomObserver = new MutationObserver((mutations) => { if (SearchPageRuntimeHelper.hasNewDomNodes(mutations)) { debouncedEnhance(); } }); searchPageDomObserver.observe(document.body, { childList: true, subtree: true }); } // ===== 已下线(2026-11-22):右下角「排序列表」悬浮按钮 + 排序卡片 ===== // 功能代码保留在 SearchListHelper 里(render / renderListItems / renderMinPriceSearch), // 只是不再实例化,恢复时把下面两行取消注释即可。 // const searchListHelper = new SearchListHelper(); // searchListHelper.render(); searchPageRuntimeStarted = true; activeSearchPageUrl = location.href; } // 搜索页判断 let isSearchPage = () => location.href.includes('so.szlcsc.com/global.html') || location.href.includes('list.szlcsc.com/brand/') || location.href.includes('list.szlcsc.com/catalog') || MroPageHelper.isMroPage(location.href); // ======================================================== // 新版本检查弹框(ScriptCat 线上脚本 @version 对比;参考 jlc_tool_2.0) const VERSION_CHECK = (() => { const APP_VERSION = (typeof GM_info !== 'undefined' && GM_info && GM_info.script && GM_info.script.version) || ''; const SCRIPT_CAT_PAGE_URL = 'https://scriptcat.org/zh-CN/script-show-page/4849'; const SCRIPT_CAT_INSTALL_URL = 'https://scriptcat.org/scripts/code/4849/JLC_SHOP_SEARCH_TOOL_2.0.user.js'; const CACHE_KEY = 'JLC_SEARCH_TOOL_VERSION_CHECK'; const SKIP_KEY = 'JLC_SEARCH_TOOL_VERSION_UPDATE_SKIP'; const MUTE_DATE_KEY = 'JLC_SEARCH_TOOL_VERSION_UPDATE_MUTE_DATE'; const CACHE_TTL = 6 * 60 * 60 * 1000; // 6 小时内不重复请求 let checking = false; // 存储:GM_* 优先(so/list/mro 多个域共享),localStorage 兜底 const storage = { get(key) { try { if (typeof GM_getValue === 'function') { const value = GM_getValue(key); if (value !== undefined && value !== null) { return value; } } } catch (error) { /* ignore */ } try { return localStorage.getItem(key); } catch (error) { return null; } }, set(key, value) { try { if (typeof GM_setValue === 'function') { GM_setValue(key, value); } } catch (error) { /* ignore */ } try { localStorage.setItem(key, value); } catch (error) { /* ignore */ } }, }; function readJson(key) { const raw = storage.get(key); if (!raw) { return null; } if (typeof raw === 'object') { return raw; } try { return JSON.parse(raw); } catch (error) { return null; } } function writeJson(key, value) { storage.set(key, JSON.stringify(value)); } function fetchRemoteScriptText() { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(new Error('GM_xmlhttpRequest unavailable')); return; } GM_xmlhttpRequest({ url: SCRIPT_CAT_INSTALL_URL, method: 'GET', timeout: 8000, onload: response => { if (response.status >= 200 && response.status < 300) { resolve(response.responseText || response.response || ''); return; } reject(new Error(`ScriptCat version request failed: ${response.status}`)); }, onerror: reject, ontimeout: () => reject(new Error('ScriptCat version request timeout')), }); }); } function maybeShowUpdateModal(remoteVersion) { const state = { localVersion: APP_VERSION, remoteVersion, skipVersion: storage.get(SKIP_KEY), muteDate: storage.get(MUTE_DATE_KEY), todayKey: VersionCheckRuntimeHelper.getTodayKey(), }; if (VersionCheckRuntimeHelper.shouldShowUpdateModal(state)) { showUpdateModal(remoteVersion); } } async function checkRemoteVersion({ force = false } = {}) { if (!APP_VERSION || checking) { return; } const cache = readJson(CACHE_KEY); const cacheMatchesCurrentApp = !!(cache && cache.localVersion === APP_VERSION && cache.remoteVersion); if (cacheMatchesCurrentApp) { maybeShowUpdateModal(cache.remoteVersion); if (!force && VersionCheckRuntimeHelper.isCacheFresh(cache, Date.now(), CACHE_TTL)) { return; } } checking = true; try { const scriptText = await fetchRemoteScriptText(); const remoteVersion = VersionCheckRuntimeHelper.parseUserscriptVersion(scriptText); if (!remoteVersion) { throw new Error('ScriptCat userscript version not found'); } writeJson(CACHE_KEY, { remoteVersion, localVersion: APP_VERSION, checkedAt: Date.now(), }); maybeShowUpdateModal(remoteVersion); } catch (error) { console.warn('[JLC] 检查新版本失败', error); } finally { checking = false; } } function ensureModalStyle() { if (document.getElementById('jlc-version-style')) { return; } const style = document.createElement('style'); style.id = 'jlc-version-style'; style.textContent = ` #jlc-version-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 2147483646; display: flex; align-items: center; justify-content: center; background: rgba(0, 0, 0, 0.45); } .jlc-version-card { position: relative; width: 460px; max-width: calc(100vw - 40px); box-sizing: border-box; padding: 18px 22px; background: #fff; border-radius: 10px; box-shadow: 0 16px 45px rgba(17, 57, 96, .22); } .jlc-version-badge { display: inline-flex; align-items: center; height: 22px; padding: 0 9px; margin-bottom: 12px; color: #fff; font-size: 12px; font-weight: 700; letter-spacing: .5px; border-radius: 999px; background: linear-gradient(90deg, #1d8dd9, #1677ff); } .jlc-version-title { color: #1f2d3d; font-size: 20px; font-weight: 700; line-height: 28px; } .jlc-version-desc { margin-top: 10px; color: #5f6b7a; font-size: 14px; line-height: 24px; } .jlc-version-desc span { color: #667085; font-weight: 600; } .jlc-version-desc strong { color: #1d8dd9; font-size: 18px; } .jlc-version-route { display: flex; align-items: center; width: fit-content; margin-top: 18px; padding: 7px 12px; color: #1d8dd9; font-size: 13px; border: 1px solid rgba(29, 141, 217, .2); border-radius: 6px; background: rgba(29, 141, 217, .06); } .jlc-version-route i { width: 28px; height: 1px; margin: 0 8px; background: #1d8dd9; } .jlc-version-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 24px; } .jlc-version-btn { padding: 5px 14px; font-size: 13px; color: #4e5969; background: #fff; border: 1px solid #dcdfe6; border-radius: 4px; cursor: pointer; } .jlc-version-btn:hover { color: #1d8dd9; border-color: #1d8dd9; } .jlc-version-btn.primary { color: #fff; background: #1d8dd9; border-color: #1d8dd9; } .jlc-version-btn.primary:hover { opacity: .9; } `; document.head.appendChild(style); } function showUpdateModal(remoteVersion) { ensureModalStyle(); if (document.getElementById('jlc-version-modal')) { return; } const mask = document.createElement('div'); mask.id = 'jlc-version-modal'; mask.innerHTML = `
NEW
发现搜索页助手新版本
当前版本 v${APP_VERSION},最新版本 v${remoteVersion}。 建议更新后继续使用。
ScriptCat安装脚本
`; document.body.appendChild(mask); const close = () => mask.remove(); mask.addEventListener('click', event => { const action = event.target && event.target.closest ? event.target.closest('[data-jlc-action]')?.getAttribute('data-jlc-action') : null; if (!action) { return; } if (action === 'skip') { storage.set(SKIP_KEY, remoteVersion); close(); window.$message?.info(`已跳过 v${remoteVersion}`); } else if (action === 'mute') { storage.set(MUTE_DATE_KEY, VersionCheckRuntimeHelper.getTodayKey()); close(); window.$message?.info('今日不再提醒更新'); } else if (action === 'update') { close(); if (typeof GM_openInTab === 'function') { GM_openInTab(SCRIPT_CAT_INSTALL_URL, { active: true, insert: true, setParent: true }); } else { window.open(SCRIPT_CAT_INSTALL_URL, '_blank'); } window.$message?.success(`检测到新版本 v${remoteVersion},已打开更新脚本`); } }); } // 诊断/测试钩子 if (typeof window !== 'undefined') { window.__JLC_VERSION_CHECK = { checkRemoteVersion, SCRIPT_CAT_INSTALL_URL, SCRIPT_CAT_PAGE_URL }; } return { checkRemoteVersion }; })(); // 新版本检查:延迟 8s 启动,避免影响首屏 setTimeout(() => { VERSION_CHECK.checkRemoteVersion(); }, 8000); setInterval(function () { if (isSearchPage()) { if (SearchPageRuntimeHelper.shouldBootstrapSearchPage(activeSearchPageUrl, location.href, searchPageRuntimeStarted)) { searchStart(); } } else if (searchPageRuntimeStarted) { disconnectSearchPageObservers(); } }, 1500) })()