Greasy Fork is available in English.

网购省钱小助手:自动查询京东、淘宝、聚划算、天猫等隐藏的优惠券;自动历史价格查询;界面优化等;低侵入、持续维护更新😈

用电脑端访问淘宝、天猫、京东等不会主动领取优惠券,此脚本可以把只有APP端能看到的或本来就隐藏的大额优惠券给查询出来,有券不领非好汉~ 脚本采用低侵入形式,不会破坏网页结构,大家可以放心使用

질문, 리뷰하거나, 이 스크립트를 신고하세요.
// ==UserScript==
// @name              网购省钱小助手:自动查询京东、淘宝、聚划算、天猫等隐藏的优惠券;自动历史价格查询;界面优化等;低侵入、持续维护更新😈
// @name:zh           网购省钱小助手:自动查询京东、淘宝、聚划算、天猫等隐藏的优惠券;自动历史价格查询;界面优化等;低侵入、持续维护更新😈
// @name:zh-TW        網購省錢小助手:自動查詢京東、淘寶、聚划算、天貓等隱藏的優惠券;自動曆史價格查詢;界面優化等;低侵入、持續維護更新😈
// @namespace         coupon_namespace_20230625
// @version           2.0.4
// @description       用电脑端访问淘宝、天猫、京东等不会主动领取优惠券,此脚本可以把只有APP端能看到的或本来就隐藏的大额优惠券给查询出来,有券不领非好汉~  脚本采用低侵入形式,不会破坏网页结构,大家可以放心使用
// @description:zh    用电脑端访问淘宝、天猫、京东等不会主动领取优惠券,此脚本可以把只有APP端能看到的或本来就隐藏的大额优惠券给查询出来,有券不领非好汉~  脚本采用低侵入形式,不会破坏网页结构,大家可以放心使用
// @description:zh-TW 用電腦端訪問淘寶、天貓、京東等不會主動領取優惠券,此指令碼或直譯式程式可以把只有APP端能看到的或本來就隱藏的大額優惠券給查詢出來,有券不領非好漢~  指令碼或直譯式程式採用低侵入形式,不會破壞網頁結構,大家可以放心使用
// @author            huahuacat
// @icon              data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAABFFJREFUWEfFl11oHFUUx/9nZne7s7PZpDUfmkANWKoQq5VqlVJUBK2BVI1QqILpLNaUlqxpRSLqQ9uQILbUNNltpImSDbXQKlJMIkR9qC0UEaJV8MVSUKs2iSZp2nRnN/txr0yanezMzmQ3G6Hn8Z5zz/nd83HnDuE2CxUS/59j27y+lKeCcaFCdKZuJuKuce/ej8YL8ZU3QCTYUEsQagFeC9Aay2CEQXA6yxk7Lzf3/5APUE6AWMhfx8AbwbE1H4dpGwL1MMZ6coEsCqAG/e8DvGUpgc22nOGg3Bw+YOfDFkANKSPg2LCc4AvZwJdSIFxn5csSQA0pv4Gj+v8InvZhl4ksgGhI6eMcil1wobwaYvWDWWp2YxJs7DL49JgtNxEapKbwiUwDA8Bcw3E+aOdBvHsdXFvfsA3A/v0LsyfeBVyCnc1VyeV6mHb1jGaUZ8FWDSkDi3W7c+PzcGx8AbGOZssA7n2diHXuBYv8DfJ5LW3MpdAzEAv6tzDw4cXqngaI7H48y0xc+xDmADqakbp0EXRnKeiOYit3VyVRup/2fHhNU+oAkS6lnQjvmHc4ap4EyfOOOIfj0XokhvosOZ11foOOTV0Bu/G7hS1t9wT6ThsAokHlFw7UZFo7N2+HY/2WZQ3D7Mn3wKZ+BWih3Qj4WAqEd+oA2t3uZfKMOdKK+rcgVN23LAAtW/FvT0GoLANcznlffMQT6H9EB4h17biHEV02R3I9uwfimjm7giV+qgOJc2fmggtV5YDHrfn60xMIr9YB1E7/Jgj8gjmK84lX4Fj3lGE5+f1XmA23WwJJb/dCWH2vQTfbux/JH8/eWhMIVFkOKvbGPYHwCh1gtrvhgVRK+DkLYH7szOupSz9ZAohr12etp6ciU0Hlq6Jy6xceHeDm0Z0VgpjMusK002tZWI5EWxvARo2TQIKQkrvPOQxToAYVbg6k1V/rg+VkQG15Dnxm2uhCdk94j3xTZgSwuAW1CdAmIVOW2gNWlxYVyRfkw8ObTRnw7wP4B4ZaraqC++W2giugnVzLgFmotLhJbhs6ZgCIdO7YQAKNGACkIrhf7SoYQKu91gMGkaVp75GvV6bXDF/DaNB/nGvPrwyRmqyv3XyotGmJdbxuNK0o6fIeHNS/ZgYAqyw4H3sJYs0mkGT9dbMD4ZNjiH8eQvLied2EfPKkfGi41JBlswM16H8T4If19RQDuzIKqLF8Dm1v4xAhFHtf9LQPnVkUQFNGOpUDJGC/bhiL34JIJAuGEH2yIh0a7s9qSDuPalDZBuDTtJ7PqOAaxFJFILDSkkZf60Cv1dYcz/I5iKMAKrXNfOo6+OhE3ghU5LmGspIGueX0kN2mnD8m/HjjXWosvosEvKaB8PFJ8AnTzWb2LkvXSXJ/IrcNNOWizQmgl6B798poKvYMgT/N/hit5/GED4mkA0ScHGKci0IUTud3olv8TGq1eTJZ0OQNkOskhepvO8B/AOOGMHhVlZkAAAAASUVORK5CYII=
// @include           *://*.taobao.com/*
// @include           *://*.tmall.com/*
// @include           *://chaoshi.detail.tmall.com/*
// @include           *://pages.tmall.com/wow/an/cs/search**
// @include           *://*.tmall.hk/*
// @include           *://*.liangxinyao.com/*
// @include           *://*.jd.com/*
// @include           *://*.jd.hk/*
// @include           *://*.yiyaojd.com/*
// @include           *://category.vip.com/suggest.php**
// @include           *://detail.vip.com/detail-*
// @include           *://www.vipglobal.hk/detail-*
// @include           *://list.vip.com/*.html
// @exclude           *://login.taobao.com/*
// @exclude           *://uland.taobao.com/*
// @exclude           *://www.taobao.com/*
// @exclude           *://map.taobao.com/*
// @exclude           *://jingfen.jd.com/*
// @exclude           *://pages.tmall.com/*
// @require           https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery/3.2.1/jquery.min.js
// @require           https://lf9-cdn-tos.bytecdntp.com/cdn/expire-1-M/jquery.qrcode/1.0/jquery.qrcode.min.js
// @connect			  tt.shuqiandiqiu.com
// @connect           j.jiayoushichang.com
// @grant             GM_openInTab
// @grant             GM.openInTab
// @grant             GM_getValue
// @grant             GM.getValue
// @grant             GM_setValue
// @grant             GM.setValue
// @grant             GM_xmlhttpRequest
// @grant             GM.xmlHttpRequest
// @license           AGPL License
// @antifeature  	  referral-link 【此提示为GreasyFork代码规范要求含有查券功能的脚本必须添加,实际使用无任何强制跳转,代码可查,请知悉】
// @charset		      UTF-8
// @run-at            document-idle
// ==/UserScript==
(function () {
	'use strict';
	/**
 * 脚本遵循AGPL License开源协议;在协议允许的范围类,可以自由修改
 * 开完万岁!!
 */
	//共有方法,全局共享
function CommonFunction(){
	this.GMgetValue = function (name, value=null) {
		let storageValue = value;
		if (typeof GM_getValue === "function") {
			storageValue = GM_getValue(name, value);
		} else if(typeof GM.setValue === "function"){
			storageValue = GM.getValue(name, value);
		}else{
			var arr = window.localStorage.getItem(name);
			if(arr != null){
				storageValue = arr
			}
		}
		return storageValue;
	};
	this.GMsetValue = function(name, value){
		if (typeof GM_setValue === "function") {
			GM_setValue(name, value);
		} else if(typeof GM.setValue === "function"){
			GM.setValue(name, value);
		}else{
			window.localStorage.setItem(name, value)
		}
	};
	this.GMaddStyle = function(css){
		var myStyle = document.createElement('style');
		myStyle.textContent = css;
		var doc = document.head || document.documentElement;
		doc.appendChild(myStyle);
	};
	this.GMopenInTab = function(url, options={"active":true, "insert":true, "setParent":true}){
		if (typeof GM_openInTab === "function") {
			GM_openInTab(url, options);
		} else {
			GM.openInTab(url, options);
		}
	};
	this.addScript = function(url){
		var s = document.createElement('script');
		s.setAttribute('src',url);
		document.body.appendChild(s);
	};
	this.randomNumber = function(){
		return Math.ceil(Math.random()*100000000);
	};
	this.request = function(mothed, url, param){   //网络请求
		return new Promise(function(resolve, reject){
			GM_xmlhttpRequest({
				url: url,
				method: mothed,
				data:param,
				onload: function(response) {
					var status = response.status;
					var playurl = "";
					if(status==200||status=='200'){
						var responseText = response.responseText;
						resolve({"result":"success", "data":responseText});
					}else{
						reject({"result":"error", "data":null});
					}
				}
			});
		})
	};
	this.addCommonHtmlCss = function(){
		var cssText = 
			`
			@keyframes fadeIn {
				0%    {opacity: 0}
				100%  {opacity: 1}
			}
			@-webkit-keyframes fadeIn {
				0%    {opacity: 0}
				100%  {opacity: 1}
			}
			@-moz-keyframes fadeIn {
				0%    {opacity: 0}
				100%  {opacity: 1}
			}
			@-o-keyframes fadeIn {
				0%    {opacity: 0}
				100%  {opacity: 1}
			}
			@-ms-keyframes fadeIn {
				0%    {opacity: 0}
				100%  {opacity: 1}
			}
			@keyframes fadeOut {
				0%    {opacity: 1}
				100%  {opacity: 0}
			}
			@-webkit-keyframes fadeOut {
				0%    {opacity: 1}
				100%  {opacity: 0}
			}
			@-moz-keyframes fadeOut {
				0%    {opacity: 1}
				100%  {opacity: 0}
			}
			@-o-keyframes fadeOut {
				0%    {opacity: 1}
				100%  {opacity: 0}
			}
			@-ms-keyframes fadeOut {
				0%    {opacity: 1}
				100%  {opacity: 0}
			}
			.web-toast-kkli9{
				position: fixed;
				background: rgba(0, 0, 0, 0.7);
				color: #fff;
				font-size: 14px;
				line-height: 1;
				padding:10px;
				border-radius: 3px;
				left: 50%;
				transform: translateX(-50%);
				-webkit-transform: translateX(-50%);
				-moz-transform: translateX(-50%);
				-o-transform: translateX(-50%);
				-ms-transform: translateX(-50%);
				z-index: 999999999999999999999999999;
				white-space: nowrap;
			}
			.fadeOut{
				animation: fadeOut .5s;
			}
			.fadeIn{
				animation:fadeIn .5s;
			}
			`;
		this.GMaddStyle(cssText);
	};
	this.webToast = function(params) {	//小提示框
		var time = params.time;
		var background = params.background;
		var color = params.color;
		var position = params.position;  //center-top, center-bottom
		var defaultMarginValue = 50;
		
		if(time == undefined || time == ''){
			time = 1500;
		}
		
		var el = document.createElement("div");
		el.setAttribute("class", "web-toast-kkli9");
		el.innerHTML = params.message;
		//背景颜色
		if(background!=undefined && background!=''){
			el.style.backgroundColor=background;
		}
		//字体颜色
		if(color!=undefined && color!=''){
			el.style.color=color;
		}
		
		//显示位置
		if(position==undefined || position==''){
			position = "center-bottom";
		}
		
		//设置显示位置,当前有种两种形式
		if(position==="center-bottom"){
			el.style.bottom = defaultMarginValue+"px"; 
		}else{
			el.style.top = defaultMarginValue+"px"; 
		}
		el.style.zIndex=999999;
		
		document.body.appendChild(el);
		el.classList.add("fadeIn");
		setTimeout(function () {
			el.classList.remove("fadeIn");
			el.classList.add("fadeOut");
			/*监听动画结束,移除提示信息元素*/
			el.addEventListener("animationend", function () {
				document.body.removeChild(el);
			});
			el.addEventListener("webkitAnimationEnd", function () {
				document.body.removeChild(el);
			});
		}, time);
	};
	this.filterStr = function(str){
		if(!str) return "";
		str = str.replace(/\t/g,"");
		str = str.replace(/\r/g,"");
		return encodeURIComponent(str)
	};
	this.getParamterQueryUrl = function(text, tag) { //查询GET请求url中的参数
		if(text.indexOf("?")!=-1){ //选取?后面的字符串,兼容window.location.search,前面的?不能去掉
			var textArray = text.split("?");
			text = "?"+textArray[textArray.length-1];
		}
		var t = new RegExp("(^|&)" + tag + "=([^&]*)(&|$)");
		var a = text.substr(1).match(t);
		if (a != null){
			return a[2];
		}
		return "";
	};
	this.getEndHtmlIdByUrl = function(url) { //获得以html结束的ID
		if(url.indexOf("?")!=-1){
			url = url.split("?")[0]
		}
		if(url.indexOf("#")!=-1){
			url = url.split("#")[0]
		}
		var splitText = url.split("/");
		var idText = splitText[splitText.length-1];
		idText = idText.replace(".html","");
		return idText;
	};
	this.getEcommercePlatform=function(url = window.location.href){
		let platform = "";
		if(url.indexOf("detail.tmall")!=-1 || url.indexOf("tmall.hk")!=-1 || url.indexOf("pages.tmall.com")!=-1){
			platform = "tmall";
		}else if(url.indexOf("taobao.com")!=-1 || url.indexOf("maiyao.liangxinyao.com")!=-1){
			platform = "taobao";
		}else if(url.indexOf("jd.com")!=-1 || url.indexOf("npcitem.jd.hk")!=-1 || url.indexOf("yiyaojd.com")!=-1){
			platform = "jd";
		}else if(url.indexOf("detail.vip.com")!=-1 || url.indexOf("www.vipglobal.hk")!=-1){
			platform = "vpinhui";
		}
		return platform;
	}
	this.isPC = function(){
		var userAgentInfo = navigator.userAgent;
		var Agents = ["Android", "iPhone","SymbianOS", "Windows Phone", "iPad", "iPod"];
		var flag = true;
		for (var v = 0; v < Agents.length; v++) {
			if (userAgentInfo.indexOf(Agents[v]) > 0) {
				flag = false;
				break;
			}
		}
		return flag;
	};
	this.getBilibiliBV=function(){
		var pathname = window.location.pathname;
		var bv = pathname.replace("/video/","").replace("/","");
		return bv;
	};
	this.getSystemOS=function(){
		var u = navigator.userAgent;
		if (!!u.match(/compatible/i) || u.match(/Windows/i)) {
			return 'windows';
		} else if (!!u.match(/Macintosh/i) || u.match(/MacIntel/i)) {
			return 'macOS';
		} else if (!!u.match(/iphone/i) || u.match(/Ipad/i)) {
			return 'ios';
		} else if (!!u.match(/android/i)) {
			return 'android';
		} else {
			return 'other';
		}
	};
	this.RPCDownloadFile = function(fileName, url, savePath="D:/", RPCURL="ws://localhost:16800/jsonrpc", RPCToken="") {		
		const self = this;
		if(!savePath){
			savePath = "D:/";
		}
		if(!RPCURL){
			RPCURL = "ws://localhost:16800/jsonrpc";
		}
		let options = { //下载配置文件
			"dir":savePath,
			"max-connection-per-server": "16",
			"header":["User-Agent:"+navigator.userAgent+"", "Cookie:"+document.cookie+"", "Referer:"+window.location.href+""]
		}
		if(!!fileName) {
			options.out = fileName;
		}
		let jsonRPC = {
			"jsonrpc": "2.0",
			"id": "huahuacat",
			"method": "aria2.addUri",
			"params": [[url], options],
		}
		if (!!RPCToken) {
			jsonRPC.params.unshift("token:" + RPCToken); // 必须要加在第一个
		}
		return new Promise(function(resolve, reject) {
			var webSocket = new WebSocket(RPCURL);
			webSocket.onerror = function(event) {
				console.log("webSocket.onerror", event);
				reject("Aria2连接错误,请打开Aria2和检查RPC设置!");
			}
			webSocket.onopen = function(){
				webSocket.send(JSON.stringify(jsonRPC));
			}
			webSocket.onmessage = function(event){
				let result = JSON.parse(event.data);
				switch (result.method) {
					case "aria2.onDownloadStart":
						resolve("Aria2 开始下载【"+fileName+"】");
						webSocket.close();
						break;
					case "aria2.onDownloadComplete":
						break;
					default:
						break;
				}
			}
		});
	};
	this.getElementObject = function(selector, allowEmpty = true, delay=10, maxDelay=2000){
		return new Promise((resolve,reject) =>{
			let totalDelay = 0;
			let element = document.querySelector(selector);
			let result = allowEmpty ? !!element : (!!element && !!element.innerHTML);
			if(result){
				resolve(element);
			}
			let elementInterval = setInterval(()=>{
				if(totalDelay >= maxDelay){ //总共检查2s,如果还是没找到,则返回
					clearInterval(elementInterval);
					resolve(null);
				}
				element = document.querySelector(selector);
				result = allowEmpty ? !!element : (!!element && !!element.innerHTML);
				if(result){
					clearInterval(elementInterval);
					resolve(element);
				}else{
					totalDelay += delay;
				}
			}, delay);
		});
	};
	/**
	 * @param {Object} time
	 * @param {Object} format
	 * 时间格式化
	 * DateFormat(new Date(dateCreated), "yyyy-MM-dd hh:mm:ss")
	 */
	this.DateFormat = function(time, format) {
		var o = {
			"M+": time.getMonth() + 1, //月份 
			"d+": time.getDate(), //日 
			"h+": time.getHours(), //小时 
			"m+": time.getMinutes(), //分 
			"s+": time.getSeconds(), //秒 
			"q+": Math.floor((time.getMonth() + 3) / 3), //季度 
			"S": time.getMilliseconds() //毫秒 
		};
		if(/(y+)/.test(format)){
			format = format.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		for(var k in o){
			if(new RegExp("(" + k + ")").test(format)){
				format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return format;
	}
}
//全局弹窗对象
const popup = (function(){
	class Popup {
		constructor() {
			this.mask = document.createElement('div')
			this.setStyle(this.mask, {
				"width": '100%',
				"height": '100%',
				"backgroundColor": 'rgba(0, 0, 0, .6)',
				"position": 'fixed',
				"left": "0px",
				"top": "0px",
				"bottom":"0px",
				"right":"0px",
				"z-index":"99999"
			})
			// 创建中间显示内容的水平并垂直居中的div
			this.content = document.createElement('div')
			this.setStyle(this.content, {
				"max-width": '450px',
				"width":"100%",
				"max-height": '600px',
				"backgroundColor": '#fff',
				"boxShadow": '0 0 2px #999',
				"position": 'absolute',
				"left": '50%',
				"top": '50%',
				"transform": 'translate(-50%,-50%)',
				"borderRadius": '3px'
			})
			// 将这个小div放在遮罩中
			this.mask.appendChild(this.content)
		}
		middleBox(param) {
			// 先清空中间小div的内容 - 防止调用多次,出现混乱
			this.content.innerHTML = ''
			let title = '默认标题内容';
			// 检测参数类型
			if({}.toString.call(param) === '[object String]') {
				title = param
			} else if({}.toString.call(param) === '[object Object]') {
				title = param.title
			}
			// 将遮罩放在body中显示
			document.body.appendChild(this.mask)
			// 给中间的小div设置默认的排版
			// 上面标题部分
			this.title = document.createElement('div')
			// 设置样式
			this.setStyle(this.title, {
				"width": '100%',
				"height": '40px',
				"lineHeight": '40px',
				"boxSizing": 'border-box',
				"background-color":"#FF4D40",
				"color": '#FFF',
				"text-align": 'center',
				"font-weight":"700",
				"font-size":"16px"
				
			})
			// 设置默认标题内容
			this.title.innerText = title
			// 将标题部分放在中间div中
			this.content.appendChild(this.title)
			// 关闭按钮
			this.closeBtn = document.createElement('div')
			// 设置内容
			this.closeBtn.innerText = '×'
			// 设置样式
			this.setStyle(this.closeBtn, {
				"textDecoration": 'none',
				"color": '#666',
				"position": 'absolute',
				"right": '10px',
				"top": '0px',
				"fontSize": '25px',
				"color": '#FFF',
				"display":"inline-block",
				"cursor":"pointer"
			})
			// 将关闭按钮放在中间小div中
			this.title.appendChild(this.closeBtn)
			this.closeBtn.onclick = () => this.close()
		}
		// 弹出提示框
		dialog(param) {
			this.middleBox(param);
			this.dialogContent = document.createElement('div')
			this.setStyle(this.dialogContent,{
				"padding":"15px",
				"max-height":"400px"
			})
			this.dialogContent.innerHTML = param.content;
			this.content.appendChild(this.dialogContent)
			param.onContentReady(this);
		}
		close() {
			document.body.removeChild(this.mask)
			window.location.reload();
		}
		setStyle(ele, styleObj) { // 设置样式的函数
			for(let attr in styleObj){
				ele.style[attr] = styleObj[attr]
			}
		}
	}
	let popup = null;
	return (function() {
		if(!popup) {
			popup = new Popup()
		}
		return popup;
	})()
})();
//全局统一方法对象
const commonFunctionObject = new CommonFunction(); 
commonFunctionObject.addCommonHtmlCss();	//统一html、css元素添加
let functionController = null;
	
	
	
	
	
	
	function QueryCoupon(){
	this.isRun = function(){
		var urls=["detail.tmall.com", "item.taobao.com", "item.jd.com", "item.yiyaojd.com", 
			"npcitem.jd.hk", "detail.tmall.hk", "detail.vip.com", "www.vipglobal.hk"];
		for(var i=0; i<urls.length;i++){
			if(window.location.host.indexOf(urls[i])!=-1){
				return true;
			}
		}
		return false;
	}
	this.getGoodsData = async function(platform){
		var goodsId = "";
		var goodsName = "";
		var href = window.location.href;
		if(platform=="taobao"){
			goodsId = commonFunctionObject.getParamterQueryUrl(window.location.search, "id");
			try{
				let titleObj = document.querySelector(".tb-main-title");
				if(!titleObj){
					titleObj = await commonFunctionObject.getElementObject("[class^='ItemHeader--mainTitle--']", false, 10, 500);
				}
				if(!!titleObj){
					goodsName = titleObj.textContent;
				}
			}catch(e){}
		}else if(platform=="tmall"){
			goodsId = commonFunctionObject.getParamterQueryUrl(window.location.search, "id");
			try{
				const titleObj = await commonFunctionObject.getElementObject("[class^='ItemHeader--mainTitle--']", false, 10, 500);
				goodsName = titleObj.textContent;
			}catch(e){}

		}else if(platform=="jd"){
			goodsId = commonFunctionObject.getEndHtmlIdByUrl(href);
			try{
				const titleObj = await commonFunctionObject.getElementObject("[class='sku-name']", false, 10, 500);
				goodsName = titleObj.textContent;
			}catch(e){}
		}else if(platform=="vpinhui"){
			goodsId = commonFunctionObject.getEndHtmlIdByUrl(href).replace("detail-","");
			try{
				const titleObj = await commonFunctionObject.getElementObject("[class='pib-title-detail']", false, 10, 500);
				goodsName = titleObj.textContent;
			}catch(e){}
		}
		var data={"goodsId":goodsId, "goodsName":commonFunctionObject.filterStr(goodsName)};
		return data;
	};
	this.randomSpmValue=function(){
		$("meta[name='data-spm']").each(function(){
			var max = 5000;
			var min = 1000;
			var randomValue = Math.floor(Math.random() * (max - min + 1) ) + min;
			var randomLetter = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
			$(this).attr("content", randomValue+randomLetter);
		});
		$("meta[name='spm-id']").each(function(){
			var max = 5000;
			var min = 1000;
			var randomValue = Math.floor(Math.random() * (max - min + 1) ) + min;
			var randomLetter = String.fromCharCode(Math.floor( Math.random() * 26) + "a".charCodeAt(0));
			$(this).attr("content", randomValue+randomLetter);
		});
		$("body").find("*").each(function(){
			$(this).removeAttr("data-spm-anchor-id");
			$(this).removeAttr("data-spm");
		});
	};
	this.runAliDeceptionSpm=function() {
		if(window.location.host.indexOf("aliyun.com")!=-1 || window.location.host.indexOf("taobao.com")!=-1 || window.location.host.indexOf("tmall.com")!=-1){
			this.randomSpmValue();
			setInterval(()=>{
				this.randomSpmValue();
			}, 2000);
		}
	};
	this.request = function(mothed, url, param){
		return new Promise(function(resolve, reject){
			GM_xmlhttpRequest({
				url: url,
				method: mothed,
				data:param,
				onload: function(response) {
					var status = response.status;
					var playurl = "";
					if(status==200||status=='200'){
						var responseText = response.responseText;
						resolve({"result":"success", "json":responseText});
					}else{
						reject({"result":"error", "json":null});
					}
				}
			});
		})
	};
	this.createQrcode = async function(platform, mscan){
		if(!mscan || mscan==="null" || !mscan.hasOwnProperty("mount") 
			|| !mscan.hasOwnProperty("html")|| !mscan.hasOwnProperty("qrcode")){
			return;
		}
		const {mount, html, qrcode, iden} = mscan;
		if(!!mount && !!html && !!qrcode && !!iden){
			$(mount).append(html);
			var canvasElement = document.getElementById("mscan"+iden);
			var width = canvasElement.getAttribute("width");
			var height = canvasElement.getAttribute("height");
			var cxt = canvasElement.getContext("2d");
			var imgData = new Image();
			imgData.src = qrcode;
			imgData.onload=function(){
				cxt.drawImage(imgData, 0, 0, width, height);
			}
		}
	};
	this.createCoupon = async function(platform, data){
		if(!data || data==="null" || !data.hasOwnProperty("css") || !data.hasOwnProperty("html")|| !data.hasOwnProperty("handler")){
			return;
		}
		const cssText = data.css, htmlText = data.html, handler = data.handler, templateId = data.templateId;
		if(!cssText || !htmlText || !handler){
			return;
		}
		$("body").prepend("<style>"+cssText+"</style>");
		
		var handlers = handler.split("@");
		for(var i=0; i<handlers.length; i++){
			var $handler = $(""+handlers[i]+"");
			if(platform=="taobao"){
				$handler.parent().after(htmlText);
			}else if(platform=="tmall"){
				$handler.parent().after(htmlText);
			}else if(platform=="jd"){
				$handler.after(htmlText);
			}else if(platform=="vpinhui"){
				$handler.after(htmlText);
			}
		}
		
		const $llkk = $("#"+templateId);
		if($llkk.length == 0){
			return;
		}
		
		const couponId = $llkk.data("id");
		const goodsPrivateUrl = "http://tt.shuqiandiqiu.com/api/private/change/coupon?no=5&v=1.0.2&platform="+platform+"&id=";
		
		if(!/\d/.test(couponId)){
			return;
		}
		
		setInterval(()=>{
			$llkk.find("*").each(function(){
				$(this).removeAttr("data-spm-anchor-id");
			});
		},400);
		
		const couponElementA = $llkk.find("a[name='cpShUrl']");
		couponElementA.unbind("click").bind("click", ()=>{
			event.stopPropagation();
			event.preventDefault();
			this.request("GET", goodsPrivateUrl+couponId, null).then((privateResultData)=>{
				if(privateResultData.result==="success" && !!privateResultData.json){
					let url = JSON.parse(privateResultData.json).url;
					if(!!url) GM_openInTab(url, {active:true});
				}
			});
		});
							
		//canvas画二维码
		var $canvasElement = $("#ca"+templateId);
		if($canvasElement.length == 0){
			return;
		}
		const qrcodeResultData = await this.request("GET", goodsPrivateUrl+couponId, null);
		if(!!qrcodeResultData && qrcodeResultData.result==="success" && !!qrcodeResultData.json){
			let img = JSON.parse(qrcodeResultData.json).img;
			if(!!img){
				var canvasElement = document.getElementById("ca"+templateId);
				var width = canvasElement.getAttribute("width");
				var height = canvasElement.getAttribute("height");
				var cxt = canvasElement.getContext("2d");
				var imgData = new Image();
				imgData.src = img;
				imgData.onload=function(){
					cxt.drawImage(imgData, 0, 0, width, height);
				}
			}
		}
	};
	this.createHtml = async function(platform, goodsId, goodsName){
		if(!platform || !goodsId){
			return;
		};
		let addition = "";
		if(platform=="vpinhui"){
			const vip = goodsId.split("-");
			addition = vip[0];
			goodsId = vip[1];
		}
		const goodsCouponUrl = "http://tt.shuqiandiqiu.com/api/coupon/discover?no=5&v=1.0.2&pl="+platform+"&id="+goodsId+"&qu="+goodsName+"&addition="+addition;
		try{
			const resutData = await this.request("GET", goodsCouponUrl, null);
			if(!!resutData && resutData.result==="success" && !!resutData.json){
				const json = JSON.parse(resutData.json);
				this.createCoupon(platform, json.data);
				this.createQrcode(platform, json.mscan);
			}
		}catch(e){
			console.log("createCouponHtml",e);
		}
	};
	this.start = async function(){
		if(this.isRun()){
			this.runAliDeceptionSpm();
			var platform = commonFunctionObject.getEcommercePlatform();
			if(!platform) return;
			//如果sku太多就折叠,不然移动端体验太差了
			if(platform=="tmall" || platform=="taobao"){
				commonFunctionObject.getElementObject("[class='skuItemWrapper']", false, 10, 1500).then((skuItemWrapper)=>{
					if(skuItemWrapper != null){
						const { style } = skuItemWrapper;
						style.maxHeight = "350px";
						style.overflow = "auto";
					}
				}).catch(()=>{});
			}
			const goodsData = await this.getGoodsData(platform);
			this.createHtml(platform, goodsData.goodsId, goodsData.goodsName);
		}
	};
}
function SearchPageObject(){
	this.intervalIsRunComplete = true;  //定时任务一个循环是否完成
	this.pickupSearchElements = function(){ //收集列表的元素
		const selectorElementList = new Array();
		const url = window.location.href;
		if(url.indexOf("://s.taobao.com/search")!=-1 || url.indexOf("://s.taobao.com/list")!=-1) { //淘宝搜索页面
			selectorElementList.push({"element":".items >.item", "page":"taobao"});
	
			selectorElementList.push({"element":".Content--content--sgSCZ12 .Card--doubleCardWrapper--L2XFE73", "page":"taobao_new"});
			selectorElementList.push({"element":".Content--content--sgSCZ12 .Card--listCardWrapper--ax09OfT", "page":"taobao_new"});
			selectorElementList.push({"element":".Content--content--sgSCZ12 .Card--doubleCardWrapperMall--uPmo5Bz", "page":"taobao_new"});
			selectorElementList.push({"element":".Content--content--sgSCZ12 .Card--listCardWrapperMall--E3jI8L4", "page":"taobao_new"});
	
		}else if(url.indexOf("taobao.com/category")!=-1){ //淘宝店铺分类
			selectorElementList.push({"element":"dl.item", "page":"taobao_category"});
		}else if(url.indexOf("taobao.com/search.htm")!=-1){ //淘宝店铺搜索
			selectorElementList.push({"element":"dl.item", "page":"taobao_shop_search"});
		}
		else if (url.indexOf("://list.tmall.com/search_product.htm")!=-1 || url.indexOf("://list.tmall.com//search_product.htm")!=-1
			|| url.indexOf("://list.tmall.com/coudan/search_product.htm")!=-1) { //天猫超市
	
			selectorElementList.push({"element":".product", "page":"tmall_chaoshi_search"});
			selectorElementList.push({"element":".chaoshi-recommend-list .chaoshi-recommend-item", "page":"tmall_chaoshi_search_new"}); //新天猫超市
	
		}else if (url.indexOf("//list.tmall.hk/search_product")!=-1) { //天猫国际
			selectorElementList.push({"element":"#J_ItemList .product", "page":"tmall_hk"});
		}else if(url.indexOf("tmall.com/category-")!=-1){ //天猫分类
			selectorElementList.push({"element":"#J_ShopSearchResult dl.item", "page":"tmall_category"});
		}else if(url.indexOf("tmall.com/category-")!=-1){ //天猫旗舰店分类
			selectorElementList.push({"element":"#J_ShopSearchResult dl.item", "page":"tmall_category"});
		}else if(url.indexOf(".tmall.com/shop/view_shop.htm")!=-1){ //天猫旗舰全部展示
			selectorElementList.push({"element":"dl.item", "page":"tmall_shop_01"});
		}else if(url.indexOf(".tmall.com/search.htm")!=-1){
			selectorElementList.push({"element":"dl.item", "page":"tmall_shop_search"});
		}
		else if(url.indexOf("//maiyao.liangxinyao.com/shop/view_shop.htm")!=-1 
			|| url.indexOf("//maiyao.liangxinyao.com/search.htm")!=-1
			|| url.indexOf("//maiyao.liangxinyao.com/category")!=-1){ //阿里大药房
			selectorElementList.push({"element":"#J_ShopSearchResult dl.item", "page":"ali_yao"});
		}
		else if (url.indexOf("//search.jd.com/Search")!=-1) { //京东搜索
			selectorElementList.push({"element":"#J_goodsList li.gl-item", "page":"jd_search"});
		}else if(url.indexOf("//search.jd.hk/Search")!=-1){ //京东国际https://search.jd.hk/Search?keyword=ds
			selectorElementList.push({"element":"#plist li.gl-item", "page":"jd_hk_search"}); //可能已弃用
			selectorElementList.push({"element":"li[class^='productList_']", "page":"jd_hk_new_search"});//20240119添加
		}else if(url.indexOf("//mall.jd.com/view_search")!=-1){ //京东大药房
			selectorElementList.push({"element":"li.jSubObject", "page":"jd_yao_search"});
		}else if(url.indexOf("www.jd.com")!=-1 && window.location.pathname=="/"){
			selectorElementList.push({"element":"#feedContent0 li.more2_item_good", "page":"jd_homepage"});
		}
		else if(url.indexOf("category.vip.com/suggest.php")!=-1){
			selectorElementList.push({"element":"#J_searchCatList .c-goods-item", "page":"vpinhui_search_page"});
		}else if(url.indexOf("://list.vip.com")!=-1){
			selectorElementList.push({"element":"#J_wrap_pro_add .c-goods-item", "page":"vpinhui_list"});
		}
		return selectorElementList;
	}
	this.createAllElementHtml=function(elementData){ //为所有的商品创建提示
		const self = this;
		$(elementData.element).each(function(){  //遍历所有的商品框
			self.createOneElementHtml($(this), elementData);
		});
		self.intervalIsRunComplete = true;
	}
	/**
	 * 为商品box添加有券提醒
	 * @param {Object} $element  每一个商品box
	 * @param {Object} elementData id and page
	 */
	this.createOneElementHtml=async function($element, elementData){  //查询到每个商品list
		if($element.attr("inspectresultx")){  //当存在时,说明已经处理过了
			return;
		}
		$element.attr("inspectresultx", "true");
		$element.css("position","relative");
		var page = elementData.page;
		var goodsDetailUrl = null;
		
		if(page==="taobao"){
			goodsDetailUrl = $element.find("a[id^='J_Itemlist_TLink_']").attr("href");
		}else if(page==="taobao_new"){
			let href = $element.attr("href");
			goodsDetailUrl = href.indexOf("http") == -1 ? (location.protocol + href) : href;
		}else if(page==="taobao_category"){
			goodsDetailUrl = $element.find(".J_TGoldData").attr("href");
		}else if(page==="taobao_shop_search"){
			goodsDetailUrl = $element.find(".J_TGoldData").attr("href");
		}else if(page==="ali_yao"){
			goodsDetailUrl = $element.find(".J_TGoldData").attr("href");
		}else if(page==="tmall_chaoshi_search"){
			let href = $element.find("div.product-img").find("a").attr("href");
			goodsDetailUrl = href.indexOf("http") ==-1 ? (location.protocol + href) : href;
		}else if(page==="tmall_chaoshi_search_new"){
			let href = !!$element.attr("href")?$element.attr("href"):$element.find("a").attr("href");
			goodsDetailUrl = href.indexOf("http") ==-1 ? (location.protocol + href) : href;
		}else if(page==="tmall_hk"){
			goodsDetailUrl = $element.find("a.productImg").attr("href");
		}else if(page==="tmall_category"){
			goodsDetailUrl = $element.find(".J_TGoldData").attr("href");
		}else if(page==="tmall_shop_01"){
			goodsDetailUrl = $element.find("dt.photo").find("a").attr("href");
		}else if(page==="tmall_shop_search"){
			goodsDetailUrl = $element.find(".J_TGoldData").attr("href");
		}
		else if(page==="jd_search"){
			goodsDetailUrl = $element.find("div.p-img").find("a").attr("href");
		}else if(page==="jd_hk_search"){
			goodsDetailUrl = $element.find("div.p-img").find("a").attr("href");
		}else if(page==="jd_hk_new_search"){
			goodsDetailUrl = $element.find("a").attr("href");
		}else if(page==="jd_yao_search"){
			goodsDetailUrl = $element.find("div.jPic").find("a").attr("href");
		}else if(page=="jd_homepage"){
			goodsDetailUrl = $element.find("a[class='more2_lk']").attr("href");
		}
		else if(page=="vpinhui_search_page"){
			goodsDetailUrl = $element.find("a").attr("href");
		}else if(page=="vpinhui_list"){
			goodsDetailUrl = $element.find("a").attr("href");
		}
		if(!goodsDetailUrl){
			return;
		}
		let analysisData = null;
		if(page.indexOf("jd_")!=-1){
			var jdId = commonFunctionObject.getEndHtmlIdByUrl(goodsDetailUrl);
			if(!!jdId){
				analysisData = {"id":jdId, "platform":"jd"};
			}
		}else if(page.indexOf("vpinhui_")!=-1){
			var vipId = commonFunctionObject.getEndHtmlIdByUrl(goodsDetailUrl).replace("detail-","");
			if(!!vipId){
				analysisData = {"id":vipId.split("-")[1], "platform":"vpinhui"};
			}
		}else{
			var platform = commonFunctionObject.getEcommercePlatform(goodsDetailUrl);
			var id = commonFunctionObject.getParamterQueryUrl(goodsDetailUrl, "id");
			if(platform && id){
				analysisData = {"id":id, "platform":platform};
			}
		}
		if(!analysisData){
			return;
		}
		try{
			const searchUrl = "http://j.jiayoushichang.com/api/ebusiness/coupon/exist/"+analysisData.platform+"?id="+analysisData.id;
			const data = await commonFunctionObject.request("GET", searchUrl, null);
			if(data.result=="success" && !!data.data){
				const tip = JSON.parse(data.data).tip;
				if(tip){
					$element.append(tip);
				}
			}
		}catch(e){
			console.log(e);
		}
	}
	this.searchPage=function(selectorElementList){
		if(!this.intervalIsRunComplete){
			return;
		}
		selectorElementList.forEach((elementData)=>{
			if(!!elementData){
				this.createAllElementHtml(elementData);
			}
		});
	}
	this.start=function(){
		const selectorElementList = this.pickupSearchElements();
		setInterval(()=>{
			this.searchPage(selectorElementList);
		}, 500);
	};
}
try{
	(new SearchPageObject()).start();
	(new QueryCoupon()).start();
}catch(e){
	console.log("优惠券查询:error:"+e);
}
	
	
	
})();