// ==UserScript==
// @name 京东图书定价全能王-终极完美合流版
// @namespace http://tampermonkey.net/
// @version 3.0
// @description 【主备一体化全能版】京东主渠道与当当核心总线无缝缝合。修复关注页异步折扣漏算,常驻手动录入(✍️)与重置。
// @author Gemini
// @match *://t.jd.com/*
// @match *://item.jd.com/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_deleteValue
// @connect item.m.jd.com
// @connect search.m.dangdang.com
// @connect *
// ==/UserScript==
(function() {
'use strict';
const CONFIG = {
FOLLOW: { card: '.item-inner', price: '.p-price' },
ITEM: { anchor: '.product-price-panel' }
};
let lastItemSku = null;
function getPageType() {
if (window.location.host.includes('item.jd.com')) return 'ITEM';
return 'FOLLOW';
}
const currentPage = getPageType();
console.log(`🚀 【京东图书定价全能王 V3.0】启动!异步折扣热补丁追加引擎已就绪。`);
// 💾 【数据库读取】
function getPriceCache(sku) {
const key = `jd_book_cache_${sku}`;
const cached = GM_getValue(key, null);
if (cached) {
try { return JSON.parse(cached); } catch (e) { return null; }
}
return null;
}
// 💾 【数据库写入】
function setPriceCache(sku, marketPrice) {
const key = `jd_book_cache_${sku}`;
const data = { marketPrice: marketPrice, time: new Date().getTime() };
GM_setValue(key, JSON.stringify(data));
}
// 💾 【数据库单重置】
function removePriceCache(sku) {
const key = `jd_book_cache_${sku}`;
GM_deleteValue(key);
}
// 🔍 【精准ISBN提取雷达 - 仅限详情页】
function getIsbnNum() {
const isbnDivs = document.querySelectorAll('div.text[title]');
for (let div of isbnDivs) {
const titleVal = div.getAttribute('title').trim();
if (/^\d{10,13}$/.test(titleVal)) {
return titleVal;
}
}
const bodyText = document.body.innerHTML;
const match = bodyText.match(/97[89]\d{10}/);
return match ? match[0] : null;
}
// 📊 【动态折算雷达】
function calculateDiscount(sku, marketPrice, elementContext) {
let currentPrice = null;
const isDetailPage = (currentPage === 'ITEM');
if (isDetailPage) {
const grayPrice = document.querySelector('.product-price-gray-line-through') || document.querySelector('.product-price--gray-line-through');
const mainPrice = document.querySelector(`.J-p-${sku}`) || document.querySelector('.p-price .price') || document.querySelector('.product-price-panel .price');
const priceEl = grayPrice || mainPrice;
if (priceEl && priceEl.innerText) {
const m = priceEl.innerText.replace(/\s/g, '').match(/\d+\.\d{1,2}/) || priceEl.innerText.replace(/\s/g, '').match(/\d+/);
if (m) currentPrice = parseFloat(m[0]);
}
} else {
const targetNode = elementContext || document.querySelector(`.gemini-btn-${sku}`)?.parentNode;
if (targetNode && targetNode.innerText) {
const m = targetNode.innerText.replace(/\s/g, '').match(/\d+\.\d{1,2}/) || targetNode.innerText.replace(/\s/g, '').match(/\d+/);
if (m) currentPrice = parseFloat(m[0]);
}
}
return (currentPrice && marketPrice > 0) ? ((currentPrice / marketPrice) * 10).toFixed(2) : null;
}
// ✍️ 【主动唤起:弹窗强制手动录入】
function handleManualInputPopup(sku, targetContainer, currentBtnNode) {
const userPrice = prompt(`【全能王常驻录入】请输入该书的正确定价(元),数据将强制覆写并永久冷冻:`);
if (userPrice !== null) {
const parsedPrice = parseFloat(userPrice);
if (!isNaN(parsedPrice) && parsedPrice > 0) {
setPriceCache(sku, parsedPrice);
console.log(`[全能王审计] 🟢 用户通过 ✍️ 图标手动录入定价: ¥${parsedPrice},缓存已被重写。`);
document.querySelectorAll(`.gemini-tag-${sku}`).forEach(el => el.remove());
const discount = calculateDiscount(sku, parsedPrice, currentPage === 'ITEM' ? null : currentBtnNode?.parentNode);
injectDisplay(targetContainer, parsedPrice, discount, sku, currentBtnNode);
} else {
alert("请输入正确的价格数字!");
}
}
}
// 🔄 终极兜底降级:触发按钮状态手动录入机制
function triggerManualInput(sku, btn, targetContainer, reason) {
console.log(`[全能王审计] SKU: ${sku} 自动查询受阻,原因: ${reason}`);
btn.innerText = "⚠️无定价(点此手动录入)";
btn.disabled = false;
btn.style.cursor = "pointer";
btn.style.background = "#f0ad4e";
btn.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
handleManualInputPopup(sku, targetContainer, btn);
};
}
// 📡 【关注页风控专用:转向引流函数】
function transformToFollowRiskState(btn) {
btn.innerText = "🧡🚫风控(请去详情页查)";
btn.style.background = "#ff6a00";
btn.disabled = false;
btn.style.cursor = "pointer";
btn.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
const cardNode = btn.closest('.item-inner') || btn.parentNode.parentNode;
const link = cardNode?.querySelector('a[href*="jd.com"]');
if(link) window.open(link.href, '_blank');
};
}
// 📡 【备用渠道:当当真核心异步数据总线】
function fetchFromBackupChannel(isbn, sku, btn, targetContainer) {
btn.innerText = "⏳主链路封锁,穿透备用总线...";
const targetUrl = `http://search.m.dangdang.com/search_ajax.php?act=get_product_flow_search&keyword=${isbn}`;
GM_xmlhttpRequest({
method: "GET",
url: targetUrl,
timeout: 6000,
headers: {
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
"X-Requested-With": "XMLHttpRequest"
},
onload: function(res) {
try {
const jsonObject = JSON.parse(res.responseText);
if (jsonObject && jsonObject.products && jsonObject.products.length > 0) {
let priceMap = {};
let selfOkPrice = null;
let maxCount = 0;
let modePrice = null;
for (let product of jsonObject.products) {
const isSpu = String(product.is_spu);
const shopId = String(product.shop_id).trim();
const price = parseFloat(product.original_price);
const nameStr = String(product.name);
if (isSpu === "1" || isSpu === "true") continue;
if (price > 0) {
if (!/全集|9册|礼盒|大套装|全套/i.test(nameStr)) {
priceMap[price] = (priceMap[price] || 0) + 1;
if (priceMap[price] > maxCount) {
maxCount = priceMap[price];
modePrice = price;
}
}
if (shopId === "0" && !/全集|9册|礼盒|大套装|全套/i.test(nameStr)) {
if (!selfOkPrice) selfOkPrice = price;
}
}
}
const finalPrice = selfOkPrice || modePrice || parseFloat(jsonObject.products[0].original_price);
if (finalPrice > 0) {
console.log(`[全能王审计] 🟢 成功通过【当当核心总线备用渠道】检索到定价: ¥${finalPrice}`);
setPriceCache(sku, finalPrice);
const discount = calculateDiscount(sku, finalPrice, btn.parentNode);
injectDisplay(targetContainer, finalPrice, discount, sku, btn);
return;
}
}
triggerManualInput(sku, btn, targetContainer, "当当总线未过滤出有效单本指标价");
} catch(e) {
triggerManualInput(sku, btn, targetContainer, "解析当当总线报文异常");
}
},
onerror: function() {
triggerManualInput(sku, btn, targetContainer, "网络故障(备用总线握手受阻)");
},
ontimeout: function() {
triggerManualInput(sku, btn, targetContainer, "备用总线响应超时限制");
}
});
}
// 📡 【主渠道入口逻辑】
function fetchPrice(sku, btn, targetContainer) {
btn.innerText = "⏳查询中...";
btn.disabled = true;
btn.style.cursor = "not-allowed";
btn.style.background = "#999";
GM_xmlhttpRequest({
method: "GET",
url: `https://item.m.jd.com/product/${sku}.html`,
timeout: 6000,
onload: function(response) {
if (response.finalUrl && response.finalUrl.includes('risk_handler')) {
if (currentPage === 'FOLLOW') {
transformToFollowRiskState(btn);
} else {
const isbn = getIsbnNum();
if (isbn) fetchFromBackupChannel(isbn, sku, btn, targetContainer);
else triggerManualInput(sku, btn, targetContainer, "京东显式拦截且详情页未提取到ISBN码");
}
return;
}
try {
const html = response.responseText;
let marketPrice = null;
let mMatch = html.match(/"linePrice"\s*:\s*\{[^}]*?"price"\s*:\s*["'](\d+\.\d{1,2})["']/i);
if (mMatch) marketPrice = parseFloat(mMatch[1]);
if (marketPrice) {
console.log(`[全能王审计] 🟢 成功通过【京东主渠道】检索到定价: ¥${marketPrice}`);
setPriceCache(sku, marketPrice);
const discount = calculateDiscount(sku, marketPrice, btn.parentNode);
injectDisplay(targetContainer, marketPrice, discount, sku, btn);
} else {
if (currentPage === 'FOLLOW') {
transformToFollowRiskState(btn);
} else {
const isbn = getIsbnNum();
if (isbn) {
fetchFromBackupChannel(isbn, sku, btn, targetContainer);
} else {
btn.innerText = "⚠️无定价(通常为套装)";
btn.style.background = "#f0ad4e";
}
}
}
} catch (e) {
if (currentPage === 'FOLLOW') transformToFollowRiskState(btn);
else {
btn.innerText = "❌解析失败";
btn.style.background = "#d9534f";
}
}
},
onerror: function() {
if (currentPage === 'FOLLOW') transformToFollowRiskState(btn);
else {
btn.innerText = "❌网络超时(重试)";
btn.disabled = false;
btn.style.cursor = "pointer";
btn.style.background = "#e4393c";
}
}
});
}
function injectDisplay(container, mPrice, discount, sku, btn) {
if (document.querySelector(`.gemini-tag-${sku}`)) return;
const isDetailPage = (currentPage === 'ITEM');
const wrap = document.createElement('span');
wrap.className = `gemini-price-tag gemini-tag-${sku}`;
// 设置唯一标识,方便后补逻辑定位
wrap.setAttribute('data-sku', sku);
wrap.setAttribute('data-market-price', mPrice);
wrap.style.cssText = isDetailPage
? "display:inline-block; margin-left:10px; color:#999; font-size:13px; vertical-align:middle;"
: "display:inline-block; margin-left:6px; color:#999; font-size:12px; vertical-align:middle;";
wrap.innerHTML = `定价:¥${mPrice}${discount ? ` [${discount}折]` : ''}`;
// 🔄 重置按钮
const resetBtn = document.createElement('a');
resetBtn.href = "javascript:void(0);";
resetBtn.innerText = "🔄";
resetBtn.title = "清除此书本地缓存,重新查询";
resetBtn.style.cssText = "margin-left:5px; text-decoration:none; font-size:11px; cursor:pointer; opacity:0.6; transition:opacity 0.2s;";
resetBtn.onmouseover = function() { this.style.opacity = "1"; };
resetBtn.onmouseout = function() { this.style.opacity = "0.6"; };
resetBtn.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
removePriceCache(sku);
wrap.remove();
};
wrap.appendChild(resetBtn);
// ✍️ 手写录入按钮(仅限详情页)
if (isDetailPage) {
const manualWriteBtn = document.createElement('a');
manualWriteBtn.href = "javascript:void(0);";
manualWriteBtn.innerText = "✍️";
manualWriteBtn.title = "强制手动修正并录入此书定价";
manualWriteBtn.style.cssText = "margin-left:6px; text-decoration:none; font-size:12px; cursor:pointer; opacity:0.6; transition:opacity 0.2s;";
manualWriteBtn.onmouseover = function() { this.style.opacity = "1"; };
manualWriteBtn.onmouseout = function() { this.style.opacity = "0.6"; };
manualWriteBtn.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
handleManualInputPopup(sku, container, null);
};
wrap.appendChild(manualWriteBtn);
}
if (btn && btn.parentNode) {
btn.parentNode.replaceChild(wrap, btn);
} else {
if (isDetailPage) {
const anchor = document.querySelector('.product-price-gray-line-through') || document.querySelector('.product-price--gray-line-through') || container;
if(anchor && anchor.parentNode) anchor.parentNode.appendChild(wrap);
} else {
container.appendChild(wrap);
}
}
}
function createButton(sku, container) {
const btn = document.createElement('button');
btn.className = `gemini-btn-${sku}`;
btn.innerText = "🔍查定价";
btn.style.cssText = "display:inline-block; margin-left:8px; padding:2px 8px; font-size:12px; color:#fff; background:#e4393c; border:none; border-radius:12px; cursor:pointer; outline:none; transition:all 0.2s;";
btn.onclick = function(e) {
e.preventDefault();
e.stopPropagation();
fetchPrice(sku, btn, container);
};
return btn;
}
function scan() {
if (currentPage === 'ITEM') {
const skuMatch = window.location.href.match(/\/(\d+)\.html/);
if (skuMatch) {
const sku = skuMatch[1];
if (lastItemSku && lastItemSku !== sku) {
document.querySelectorAll('[class*="gemini-tag-"], [class*="gemini-btn-"], .gemini-price-tag').forEach(el => el.remove());
}
lastItemSku = sku;
const existTag = document.querySelector(`.gemini-tag-${sku}`);
if (existTag) {
// 详情页折扣后补兜底
const discountInside = existTag.querySelector('.gemini-discount-inside');
if (discountInside && discountInside.innerHTML === '') {
const mPrice = parseFloat(existTag.getAttribute('data-market-price'));
const discount = calculateDiscount(sku, mPrice, null);
if (discount) {
discountInside.innerHTML = ` [${discount}折]`;
}
}
} else if (!document.querySelector(`.gemini-btn-${sku}`)) {
const anchor = document.querySelector(CONFIG.ITEM.anchor);
if (anchor) {
const cache = getPriceCache(sku);
if (cache) {
console.log(`[全能王审计] 🟢 SKU: ${sku} 详情页冷冻库缓存直出。`);
const discount = calculateDiscount(sku, cache.marketPrice, null);
injectDisplay(anchor, cache.marketPrice, discount, sku, null);
} else {
const btn = createButton(sku, anchor);
const grayPrice = document.querySelector('.product-price-gray-line-through') || document.querySelector('.product-price--gray-line-through');
if (grayPrice && grayPrice.parentNode) {
grayPrice.parentNode.insertBefore(btn, grayPrice.nextSibling);
} else if (anchor.parentNode) {
anchor.parentNode.appendChild(btn);
}
}
}
}
}
} else {
document.querySelectorAll(CONFIG.FOLLOW.card).forEach(card => {
const link = card.querySelector('a[href*="jd.com"]');
const priceArea = card.querySelector(CONFIG.FOLLOW.price);
if (link && priceArea) {
const match = link.href.match(/\/(\d{6,15})/);
if (match) {
const sku = match[1];
const existTag = card.querySelector(`.gemini-tag-${sku}`);
if (existTag) {
// ✨【核心修复点】关注页折扣异步后补机制
const discountInside = existTag.querySelector('.gemini-discount-inside');
if (discountInside && discountInside.innerHTML === '') {
const mPrice = parseFloat(existTag.getAttribute('data-market-price'));
const discount = calculateDiscount(sku, mPrice, priceArea);
if (discount) {
console.log(`[全能王审计] ⚡ SKU: ${sku} 现价已加载,异步热补丁追补折扣:[${discount}折]`);
discountInside.innerHTML = ` [${discount}折]`;
}
}
} else if (!card.querySelector(`.gemini-btn-${sku}`)) {
const cache = getPriceCache(sku);
if (cache) {
console.log(`[全能王审计] 🟢 SKU: ${sku} 关注页冷冻库缓存同步。`);
const holder = document.createElement('span');
priceArea.appendChild(holder);
const discount = calculateDiscount(sku, cache.marketPrice, priceArea);
injectDisplay(priceArea, cache.marketPrice, discount, sku, holder);
} else {
const btn = createButton(sku, priceArea);
priceArea.appendChild(btn);
}
}
}
}
});
}
}
setInterval(scan, 1500);
})();