在ff下报错event is not defined以及document.all和document.getElemnetById的区别

本文介绍了在不同浏览器中处理鼠标和键盘事件的方法,探讨了如何兼容IE与Firefox等浏览器间的事件对象差异,并提供了具体的示例代码。
FF 。event 仅在事件发生的瞬间有效。

document.body.onclick=function(e){
e=e||window.event;

};

例子1:

function test()

{

e=e||window.event;//firebug会报错

}

document.all可以判断浏览器是否为ie,微软的东西

document.getElemnetById支持W3c 能更加兼容多个浏览器



e.keyCode=13在ff下失效

function test(e)

{

window.event ?e.keyCode:e.which

}



例子2:测试通过

<script type="text/javascript">
function show_coords(event)
{
x=event.clientX
y=event.clientY
alert("X 坐标: " + x + ", Y 坐标: " + y)
}
</script>
</head>

<body onmousedown="show_coords(event)">
<p>请在文档中点击。提示框会显示出指针的 x 和 y 坐标。</p>

如果将event改成e则报错


(function (event) { event = event || document; let rgba = { r: 0, g: 0, b: 0, a: 1 }, hsb = { h: 0, s: 100, b: 100 }; let Initial = null, setTime = null, throttle = null; function ColorTool(str) { ColorTool.prototype.Ele = { body: document.querySelector('body'), main: document.querySelector('.main'), sample: document.querySelector('.sample'), ColorToolContainer: document.querySelector('.ColorToolContainer'), PanelContainer: document.querySelector('.PanelContainer'), panelCanvas: document.querySelector('#panelCanvas'), DotOne: document.querySelector('.DotOne'), Discoloration: document.querySelector('.Discoloration'), DotTwo: document.querySelector('.DotTwo'), input: document.querySelectorAll('input'), ControlButton: document.querySelector('.control>button'), LeftAndRightlSpan: document.querySelectorAll('.LeftAndRight>span'), InputBoxOne: document.querySelector('.InputBoxOne'), InputBoxTwo: document.querySelector('.InputBoxTwo'), InputBoxThree: document.querySelector('.InputBoxThree'), getColor: document.querySelector(".getColor"), constant: 0 }; Initial = str; return new ColorTool.prototype.init(str); } ColorTool.prototype.init = function (str) { ColorTool.prototype.initANDsetColor(str); ColorTool.prototype.getColorFun(); return this; } ColorTool.prototype.init.prototype = ColorTool.prototype; ColorTool.prototype.then = function (parameter) { ColorTool.prototype.then.prototype.thenFun = parameter; } ColorTool.setColor = function (str) { if (ColorTool.prototype.initANDsetColor) { ColorTool.prototype.initANDsetColor(str); } else { throw new Error('未调用ColorTool函数'); } } ColorTool.prototype.getColorFun = function () { if ('EyeDropper' in window) { // 判断是否支持这个api const eyeDropper = new EyeDropper(); // 创建对象 ColorTool.prototype.Ele.getColor.addEventListener('click', async () => { ColorTool.prototype.Ele.body.style.cssText = 'width:30px;height:30px;min-width:auto;min-height:auto;display:none;'; ColorTool.prototype.Ele.main.style.display = 'none'; await new Promise(resolve => setTimeout(resolve, 60)); try { const ColorResult = await eyeDropper.open();// 取得吸取结果 ColorTool.setColor(ColorResult.sRGBHex);// 取得颜色并设置颜色 chrome.storage.local.get({ history: [] }, data => { const hist = data.history; hist.unshift(ColorResult.sRGBHex); if (hist.length > 20) hist.pop(); chrome.storage.local.set({ history: hist }, () => { ColorTool.prototype.Ele.main.style.display = 'block'; ColorTool.prototype.Ele.body.style.cssText = 'width: 100vw;min-width: 256px;height:100vh;min-height: 329px;display:flex;'; }); }); } catch (e) { console.log( '%c%s', 'border: 1px solid white;border-radius: 5px;padding: 2px 5px;color: white;font-weight: bold;background-color: #ab5a5a;', '发生了一些意外!\nSomething unexpected happened!'); } }); } } ColorTool.prototype.initANDsetColor = function (str) { if (str.match(/rgb\(|\Rgb\(/g) && str.match(/\)|\);/g) && str.match(/,/g)) { if (str.match(/,/g).length === 2) { str = str.replace(/rgb\(|\Rgb\(/g, '').replace(/\)|\);/g, ''); let strArr = str.split(','); ColorTool.prototype.Ele.input[1].value = parseInt(strArr[0]); ColorTool.prototype.Ele.input[2].value = parseInt(strArr[1]); ColorTool.prototype.Ele.input[3].value = parseInt(strArr[2]); ColorTool.prototype.RgbInput(); } } else { ColorTool.prototype.Ele.input[0].value = str; ColorTool.prototype.HexInput(); } ColorTool.prototype.EventCollection(); } ColorTool.prototype.hsbToRgb = function (hsb) { var rgb = {}; var h = hsb.h; var s = hsb.s * 255 / 100; var v = hsb.b * 255 / 100; if (s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255 - s) * v / 255; var t3 = (t1 - t2) * (h % 60) / 60; if (h === 360) h = 0; if (h < 60) { rgb.r = t1; rgb.b = t2; rgb.g = t2 + t3 } else if (h < 120) { rgb.g = t1; rgb.b = t2; rgb.r = t1 - t3 } else if (h < 180) { rgb.g = t1; rgb.r = t2; rgb.b = t2 + t3 } else if (h < 240) { rgb.b = t1; rgb.r = t2; rgb.g = t1 - t3 } else if (h < 300) { rgb.b = t1; rgb.g = t2; rgb.r = t2 + t3 } else if (h < 360) { rgb.r = t1; rgb.g = t2; rgb.b = t1 - t3 } else { rgb.r = 0; rgb.g = 0; rgb.b = 0 } } return { r: Math.round(rgb.r), g: Math.round(rgb.g), b: Math.round(rgb.b) }; } ColorTool.prototype.rgbToHex = function (rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; hex.map(function (str, i) { if (str.length == 1) { hex[i] = '0' + str; } }); return hex.join(''); } ColorTool.prototype.hexToRgb = function (hex) { var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16); return { r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF) }; } ColorTool.prototype.hexToHsb = function (hex) { return this.rgbToHsb(this.hexToRgb(hex)); } ColorTool.prototype.rgbToHsb = function (rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; hsb.s = max != 0 ? 255 * delta / max : 0; if (hsb.s != 0) { if (rgb.r == max) hsb.h = (rgb.g - rgb.b) / delta; else if (rgb.g == max) hsb.h = 2 + (rgb.b - rgb.r) / delta; else hsb.h = 4 + (rgb.r - rgb.g) / delta; } else hsb.h = -1; hsb.h *= 60; if (hsb.h < 0) hsb.h += 360; hsb.s *= 100 / 255; hsb.b *= 100 / 255; return hsb; } ColorTool.prototype.rgbToHsl = function (rgb) { var HslArray = { h: rgb.r / 255, s: rgb.g / 255, l: rgb.b / 255 }; var max = Math.max(HslArray.h, HslArray.s, HslArray.l); var min = Math.min(HslArray.h, HslArray.s, HslArray.l); var difference = max - min; var hsl = { h: 0, s: 0, l: 0 }; if (max == min) { hsl.h = 0; } else if (max == HslArray.h && HslArray.s >= HslArray.l) { hsl.h = 60 * (HslArray.s - HslArray.l) / difference; } else if (max == HslArray.h && HslArray.s < HslArray.l) { hsl.h = 60 * (HslArray.s - HslArray.l) / difference + 360; } else if (max == HslArray.s) { hsl.h = 60 * (HslArray.l - HslArray.h) / difference + 120; } else if (max == HslArray.l) { hsl.h = 60 * (HslArray.h - HslArray.s) / difference + 240; } var sum = max + min; hsl.l = sum / 2; if (hsl.l == 0 || max == min) { hsl.s = 0; } else if (0 < hsl.l && hsl.l <= 0.5) { hsl.s = difference / sum; } else { hsl.s = difference / (2 - sum); } hsl.h = Math.round(hsl.h); return hsl; } ColorTool.prototype.hslToRgb = function (H = 0, S = 0, L = 0) { S /= 100; L /= 100; let CXM = { C: (1 - Math.abs(2 * L - 1)) * S, X: ((1 - Math.abs(2 * L - 1)) * S) * (1 - Math.abs(((H / 60) % 2) - 1)), M: L - ((1 - Math.abs(2 * L - 1)) * S) / 2 } let vRGB = [] if (H >= 0 && H < 60) { vRGB.push(CXM.C, CXM.X, 0) } else if (H >= 60 && H < 120) { vRGB.push(CXM.X, CXM.C, 0) } else if (H >= 120 && H < 180) { vRGB.push(0, CXM.C, CXM.X) } else if (H >= 180 && H < 240) { vRGB.push(0, CXM.X, CXM.C) } else if (H >= 240 && H < 300) { vRGB.push(CXM.X, 0, CXM.C) } else if (H >= 300 && H < 360) { vRGB.push(CXM.C, 0, CXM.X) } const [vR, vG, vB] = vRGB let RGB = { r: Math.round(255 * (vR + CXM.M)), g: Math.round(255 * (vG + CXM.M)), b: Math.round(255 * (vB + CXM.M)) } return RGB } ColorTool.prototype.setValue = function (rgb) { ColorTool.prototype.Ele.input[0].value = "#" + this.rgbToHex(rgb); ColorTool.prototype.Ele.input[1].value = rgb.r; ColorTool.prototype.Ele.input[2].value = rgb.g; ColorTool.prototype.Ele.input[3].value = rgb.b; let hsl = ColorTool.prototype.rgbToHsl(rgb); ColorTool.prototype.Ele.input[4].value = hsl.h; ColorTool.prototype.Ele.input[5].value = Math.round(hsl.s * 100) + "%"; ColorTool.prototype.Ele.input[6].value = Math.round(hsl.l * 100) + "%"; } ColorTool.prototype.changeColor = function () { let rgb = this.hsbToRgb(hsb); this.setValue(rgb); rgba.r = rgb.r; rgba.g = rgb.g; rgba.b = rgb.b; localStorage.setItem("ColorToolStorage", "#" + this.rgbToHex(rgb)); ColorTool.prototype.Ele.sample.style.backgroundColor = 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgba.a + ')'; if (!(rgb.r >= 196 && rgb.g >= 196 && rgb.b >= 196)) { document.documentElement.style.setProperty('--MyColor', 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgba.a + ')'); } clearTimeout(throttle); throttle = setTimeout(function () { if (ColorTool.prototype.thenFunExistence('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')')) { ColorTool.prototype.then.prototype.thenFun('rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')'); } clearTimeout(throttle); }, 36); } ColorTool.prototype.thenFunExistence = function (ColorData) { if (ColorTool.prototype.then.prototype.thenFun) { return true; } else { clearTimeout(setTime); setTime = setTimeout(function () { //延时防止调用thenFun时发生越界 if (ColorTool.prototype.thenFunExistence(ColorData)) { ColorTool.prototype.then.prototype.thenFun(ColorData); } clearTimeout(setTime); }, 5); } return false; } ColorTool.prototype.PanelCalculation = function (x, y) { let MaxLeft = Math.max(0, Math.min(x, 216)); let MaxTop = Math.max(0, Math.min(y, 124)); hsb.s = 100 * MaxLeft / 216; hsb.b = 100 * (124 - MaxTop) / 124; this.changeColor(); } ColorTool.prototype.PanelColor = function (ColorData) { let canvas = ColorTool.prototype.Ele.panelCanvas; if (canvas && canvas.getContext) { let ctx = canvas.getContext("2d"); // 底色填充,也就是(举例红色)到白色 let gradientBase = ctx.createLinearGradient(3, 0, 216, 0); gradientBase.addColorStop(1, ColorData); gradientBase.addColorStop(0, "rgba(255,255,255,1)"); ctx.fillStyle = gradientBase; ctx.fillRect(0, 0, 216, 124); // 第二次填充,黑色到透明 let gradientScreen = ctx.createLinearGradient(0, 3, 0, 124); gradientScreen.addColorStop(0, "transparent"); gradientScreen.addColorStop(1, "rgba(0,0,0,1)"); ctx.fillStyle = gradientScreen; ctx.fillRect(0, 0, 216, 124); } } ColorTool.prototype.BarCalculation = function (x) { let Left = Math.max(0, Math.min(x, 216)); hsb.h = 360 * Left / 216; let rgb = this.hsbToRgb({ h: hsb.h, s: 100, b: 100 }); ColorTool.prototype.PanelColor('rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + rgba.a + ')'); this.changeColor(); // rgba.a = X / elem_width;//调透明度的 } ColorTool.prototype.panel = function (event) { ColorTool.prototype.Ele.DotOne.style.top = (event.offsetY - (ColorTool.prototype.Ele.DotOne.offsetHeight / 2)) + "px"; ColorTool.prototype.Ele.DotOne.style.left = (event.offsetX - (ColorTool.prototype.Ele.DotOne.offsetWidth / 2)) + "px"; ColorTool.prototype.PanelCalculation(event.offsetX, event.offsetY); } ColorTool.prototype.DiscolorationFun = function (event) { ColorTool.prototype.Ele.DotTwo.style.left = (event.offsetX - (ColorTool.prototype.Ele.DotTwo.offsetWidth / 2)) + "px"; ColorTool.prototype.BarCalculation(event.offsetX); } ColorTool.prototype.DotOneFun = function (event) { ColorTool.prototype.Ele.PanelContainer.removeEventListener("click", ColorTool.prototype.panel); let DotOneTop = event.offsetY > 0 ? event.offsetY : 0; let DotOneLeft = event.offsetX > 0 ? event.offsetX : 0; document.onmousemove = function (e) { e.preventDefault(); let PanelContainerWidth = ColorTool.prototype.Ele.PanelContainer.clientWidth; let PanelContainerHeight = ColorTool.prototype.Ele.PanelContainer.clientHeight; let OneTop = e.clientY - (ColorTool.prototype.Ele.ColorToolContainer.offsetTop + DotOneTop); let OneLeft = e.clientX - (ColorTool.prototype.Ele.ColorToolContainer.offsetLeft + DotOneLeft); OneTop = OneTop <= -(ColorTool.prototype.Ele.DotOne.offsetHeight / 2) ? -(ColorTool.prototype.Ele.DotOne.offsetHeight / 2) + 1 : OneTop; OneTop = OneTop >= (PanelContainerHeight - (ColorTool.prototype.Ele.DotOne.offsetHeight / 2)) ? (PanelContainerHeight - (ColorTool.prototype.Ele.DotOne.offsetHeight / 2)) : OneTop; OneLeft = OneLeft <= -(ColorTool.prototype.Ele.DotOne.offsetWidth / 2) ? -(ColorTool.prototype.Ele.DotOne.offsetWidth / 2) : OneLeft; OneLeft = OneLeft >= (PanelContainerWidth - (ColorTool.prototype.Ele.DotOne.offsetWidth / 2)) ? (PanelContainerWidth - (ColorTool.prototype.Ele.DotOne.offsetWidth / 2)) : OneLeft; ColorTool.prototype.Ele.DotOne.style.top = OneTop + "px"; ColorTool.prototype.Ele.DotOne.style.left = OneLeft + "px"; ColorTool.prototype.PanelCalculation((e.clientX - ColorTool.prototype.Ele .ColorToolContainer.offsetLeft), (e.clientY - ColorTool.prototype.Ele.ColorToolContainer.offsetTop)); } document.onmouseup = function (e) { document.onmousemove = null; document.onmouseup = null; let delayed = setTimeout(function () { ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype.panel); clearTimeout(delayed); }, 10); } } ColorTool.prototype.DotTwoFun = function (event) { ColorTool.prototype.Ele.Discoloration.removeEventListener("click", ColorTool.prototype .DiscolorationFun); let DotTwoLeft = event.offsetX > 0 ? event.offsetX : 0; document.onmousemove = function (e) { e.preventDefault(); let TwoLeft = e.clientX - (ColorTool.prototype.Ele.ColorToolContainer.offsetLeft + DotTwoLeft); let DiscolorationWidth = ColorTool.prototype.Ele.Discoloration.clientWidth; TwoLeft = TwoLeft <= -(ColorTool.prototype.Ele.DotTwo.offsetWidth / 2) ? -(ColorTool.prototype.Ele.DotTwo.offsetWidth / 2) : TwoLeft; TwoLeft = TwoLeft >= (DiscolorationWidth - (ColorTool.prototype.Ele.DotTwo.offsetWidth / 2)) ? (DiscolorationWidth - (ColorTool.prototype.Ele.DotTwo.offsetWidth / 2)) : TwoLeft; ColorTool.prototype.Ele.DotTwo.style.left = TwoLeft + "px"; ColorTool.prototype.BarCalculation(e.clientX - ColorTool.prototype.Ele.ColorToolContainer .offsetLeft); } document.onmouseup = function (e) { document.onmousemove = null; document.onmouseup = null; let delayed = setTimeout(function () { ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool .prototype.DiscolorationFun); clearTimeout(delayed); }, 10); } } ColorTool.prototype.setDistance = function (hsb) { ColorTool.prototype.Ele.DotOne.style.top = parseInt(((100 - hsb.b) * 124 / 100) - (ColorTool.prototype.Ele.DotOne.offsetHeight / 2)) + "px"; ColorTool.prototype.Ele.DotOne.style.left = parseInt((hsb.s * 216 / 100) - (ColorTool.prototype.Ele.DotOne.offsetWidth / 2)) + "px"; ColorTool.prototype.Ele.DotTwo.style.left = parseInt((hsb.h / 360 * 216) - (ColorTool.prototype.Ele.DotTwo.offsetWidth / 2)) + "px"; this.PanelCalculation(hsb.s * 216 / 100, (100 - hsb.b) * 124 / 100); this.BarCalculation(hsb.h / 360 * 216); } ColorTool.prototype.SpecialSymbol = function (str) { var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~!@#¥……&*()——|{}【】‘;:”“'。,、? ]"); if (pattern.test(str)) { return true; } return false; } ColorTool.prototype.HexInput = function (Blur) { let ColorToolThis = ColorTool.prototype; if (!ColorTool.prototype.Ele.input[0].value) { return null; } if (ColorTool.prototype.Ele.input[0].value[0] !== "#") { ThisValuePro = "#" + ColorTool.prototype.Ele.input[0].value; } else { ThisValuePro = ColorTool.prototype.Ele.input[0].value.substring(1); } if (!ColorToolThis.SpecialSymbol(ThisValuePro)) { if (ThisValuePro.length === 6) { ColorToolThis.setDistance(ColorToolThis.hexToHsb(ColorTool.prototype.Ele.input[0].value)); } else if (Blur) { if (ThisValuePro.length === 3) { let NewValue = ThisValuePro[0] + ThisValuePro[0] + ThisValuePro[1] + ThisValuePro[1] + ThisValuePro[ 2] + ThisValuePro[2]; ColorToolThis.setDistance(ColorToolThis.hexToHsb(NewValue)); } } } } ColorTool.prototype.RgbInput = function (event) { let ColorToolThis = ColorTool.prototype; if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[1].value) && !ColorToolThis .SpecialSymbol(ColorToolThis.Ele.input[2].value) && !ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[3].value)) { if (parseInt(ColorToolThis.Ele.input[1].value) >= 0 && parseInt(ColorToolThis.Ele.input[2] .value) >= 0 && parseInt(ColorToolThis.Ele.input[3].value) >= 0) { if (parseInt(ColorToolThis.Ele.input[1].value) <= 255 && parseInt(ColorToolThis.Ele.input[2] .value) <= 255 && parseInt(ColorToolThis.Ele.input[3] .value) <= 255) { ColorToolThis.setDistance(ColorToolThis.rgbToHsb({ r: parseInt(ColorToolThis.Ele.input[1].value), g: parseInt(ColorToolThis.Ele.input[2].value), b: parseInt(ColorToolThis.Ele.input[3].value) })); } } } ColorTool.prototype.hslToRgb(0, 100, 50); } ColorTool.prototype.HslInput = function (event) { let ColorToolThis = ColorTool.prototype; if (!ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[4].value) && !ColorToolThis .SpecialSymbol(ColorToolThis.Ele.input[5].value) && !ColorToolThis.SpecialSymbol(ColorToolThis.Ele.input[6].value)) { if (parseInt(ColorToolThis.Ele.input[4].value) >= 0 && parseInt(ColorToolThis.Ele.input[5] .value) >= 0 && parseInt(ColorToolThis.Ele.input[6].value) >= 0) { if (parseInt(ColorToolThis.Ele.input[4].value) <= 360 && parseInt(ColorToolThis.Ele.input[5] .value) <= 100 && parseInt(ColorToolThis.Ele.input[6] .value) <= 100) { ColorToolThis.setDistance( ColorToolThis.rgbToHsb( ColorTool.prototype.hslToRgb( parseInt(ColorToolThis.Ele.input[4].value), parseInt(ColorToolThis.Ele.input[5].value), parseInt(ColorToolThis.Ele.input[6].value) ) ) ); } } } } ColorTool.prototype.NoneOrFlex = function (constant) { ColorTool.prototype.Ele.InputBoxOne.style.display = "none"; ColorTool.prototype.Ele.InputBoxTwo.style.display = "none"; ColorTool.prototype.Ele.InputBoxThree.style.display = "none"; if (constant === 0) { ColorTool.prototype.Ele.InputBoxOne.style.display = "block"; } else if (constant === 1) { ColorTool.prototype.Ele.InputBoxTwo.style.display = "flex"; } else { ColorTool.prototype.Ele.InputBoxThree.style.display = "flex"; } } ColorTool.prototype.EventCollection = function () { ColorTool.prototype.Ele.PanelContainer.addEventListener('click', ColorTool.prototype.panel); ColorTool.prototype.Ele.Discoloration.addEventListener('click', ColorTool.prototype .DiscolorationFun); ColorTool.prototype.Ele.DotOne.addEventListener('mousedown', ColorTool.prototype.DotOneFun); ColorTool.prototype.Ele.DotTwo.addEventListener('mousedown', ColorTool.prototype.DotTwoFun); ColorTool.prototype.Ele.input[0].addEventListener('input', function () { ColorTool.prototype.HexInput(false) }); ColorTool.prototype.Ele.input[0].addEventListener('blur', function () { ColorTool.prototype.HexInput(true) }); ColorTool.prototype.Ele.input[1].addEventListener('input', ColorTool.prototype.RgbInput); ColorTool.prototype.Ele.input[2].addEventListener('input', ColorTool.prototype.RgbInput); ColorTool.prototype.Ele.input[3].addEventListener('input', ColorTool.prototype.RgbInput); ColorTool.prototype.Ele.input[4].addEventListener('input', ColorTool.prototype.HslInput); ColorTool.prototype.Ele.input[5].addEventListener('input', ColorTool.prototype.HslInput); ColorTool.prototype.Ele.input[6].addEventListener('input', ColorTool.prototype.HslInput); ColorTool.prototype.Ele.ControlButton.addEventListener('click', function () { ColorTool.prototype.init(Initial); }); ColorTool.prototype.Ele.LeftAndRightlSpan[0].addEventListener('click', function () { ColorTool.prototype.Ele.constant = --ColorTool.prototype.Ele.constant >= 0 ? --ColorTool.prototype.Ele.constant : 1; ColorTool.prototype.NoneOrFlex(++ColorTool.prototype.Ele.constant); }); ColorTool.prototype.Ele.LeftAndRightlSpan[1].addEventListener('click', function () { ColorTool.prototype.Ele.constant = ++ColorTool.prototype.Ele.constant <= 2 ? ++ColorTool.prototype.Ele.constant : 1; ColorTool.prototype.NoneOrFlex(--ColorTool.prototype.Ele.constant); }); } event.ColorTool = ColorTool; })(window);把它改写成类
最新发布
09-25
// ====== 环境修复与全局对象安全 ====== (function() { // 安全获取全局对象的函数(支持严格模式所有环境) const getGlobalObject = () => { // 1. 优先使用现代标准 globalThis if (typeof globalThis !== 'undefined') return globalThis; // 2. 处理严格模式限制 try { const globalFromFn = Function('return this')(); if (globalFromFn) return globalFromFn; } catch (e) { console.warn('[EnvFix] Function constructor blocked in strict mode'); } // 3. 环境特定对象 if (typeof global !== 'undefined') return global; // Node.js if (typeof window !== 'undefined') return window; // 浏览器 if (typeof self !== 'undefined') return self; // Web Worker // 4. Cocos Creator 原生环境特殊处理 if (typeof cc !== 'undefined' && cc.sys && cc.sys.__globalAdapter) { return cc.sys.__globalAdapter; } // 5. 最后手段:创建新的全局对象 console.error('[EnvFix] Unable to determine global object, creating new'); return {}; }; const globalObj = getGlobalObject(); // 修复关键全局变量(使用 Object.defineProperty 防止覆盖) const defineGlobal = (name, value) => { if (typeof globalObj[name] === 'undefined') { Object.defineProperty(globalObj, name, { value, writable: true, configurable: true, enumerable: true }); console.log(`[EnvFix] Defined global: ${name}`); } }; // 定义关键全局对象 defineGlobal('global', globalObj); defineGlobal('self', globalObj); defineGlobal('globalThis', globalObj); defineGlobal('window', globalObj); // 原生平台特殊处理 if (cc && cc.sys && cc.sys.isNative) { // 确保 XMLHttpRequest 存在 if (typeof XMLHttpRequest === 'undefined') { defineGlobal('XMLHttpRequest', function() { return cc.loader.getXMLHttpRequest(); }); } // 确保 document 对象存在 if (typeof document === 'undefined') { defineGlobal('document', { createElement: () => ({ appendChild: () => {} }), head: { appendChild: () => {} }, body: { appendChild: () => {} } }); } // 确保 location 对象存在 if (typeof location === 'undefined') { defineGlobal('location', { href: 'file://', protocol: 'file:', hostname: 'localhost', host: 'localhost', origin: 'file://' }); } console.log('[EnvFix] Native environment patched'); } // 确保 require 函数存在 if (typeof globalObj.require === 'undefined') { defineGlobal('require', function(module) { if (globalObj.__modules && globalObj.__modules[module]) { return globalObj.__modules[module]; } console.warn(`[RequireFallback] Module '${module}' not found`); return {}; }); } })(); // ====== 引擎初始化保护系统 ====== const EngineReady = (function() { let _promise = null; let _resolve = null; let _isReady = false; let _checkInterval = null; const safeCheckEngine = () => { // 引擎已初始化 if (cc && cc.game && cc.game._isEngineInited) { return true; } // 尝试监听初始化事件 if (cc && cc.game && cc.game.once) { const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited'; cc.game.once(eventName, () => { _resolve && _resolve(); _isReady = true; _checkInterval && clearInterval(_checkInterval); }); return true; } return false; }; return { get isReady() { return _isReady; }, get promise() { return _promise; }, init() { if (!_promise) { _promise = new Promise(resolve => { _resolve = () => { _isReady = true; resolve(); _checkInterval && clearInterval(_checkInterval); }; // 首次检查 if (safeCheckEngine()) return; // 轮询检查 _checkInterval = setInterval(() => { safeCheckEngine() && _resolve(); }, 100); }); } return _promise; }, safeAccess(callback) { if (_isReady) { try { return callback(); } catch (e) { console.error('[EngineSafe] Error:', e); } } return _promise.then(callback).catch(e => { console.error('[EngineSafe] Async error:', e); }); } }; })(); EngineReady.init(); // ====== 游戏主入口 ====== async function gameMainEntry() { try { console.log('[Main] Waiting for engine initialization...'); await EngineReady.promise; console.log('[Main] Engine ready'); // 基本引擎配置 EngineReady.safeAccess(() => { if (cc.view) { cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); } }); // 加载SDK await loadGravityEngineSDK(); // 加载启动场景 await loadStartScene(); } catch (error) { console.error('[Main] Initialization failed:', error); try { cc.director.loadScene('start'); } catch (fallbackError) { displayErrorFallback('启动失败\n请重启应用'); } } } // 错误显示后备方案 function displayErrorFallback(message) { try { const errorDiv = document.createElement('div'); errorDiv.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: black; color: white; display: flex; justify-content: center; align-items: center; z-index: 9999; font: 24px Arial, sans-serif; text-align: center; white-space: pre-line; padding: 20px; `; errorDiv.textContent = message; document.body.appendChild(errorDiv); } catch (e) { console.error('[Fallback] Display failed:', e); } } // ====== SDK加载器增强版 ====== async function loadGravityEngineSDK() { // 使用相对路径解决加载问题 const sdkPaths = [ './assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js', '_plugs/lib/gravityengine.mg.cocoscreator.min.js', 'lib/gravityengine.mg.cocoscreator.min.js' ]; for (const path of sdkPaths) { try { // 关键修复:在加载 SDK 前确保全局对象完整 ensureGlobalEnvironment(); // JSB 特殊处理:使用 require 加载 if (cc.sys.isNative && cc.sys.__globalAdapter?.require) { cc.sys.__globalAdapter.require(path); console.log('[SDK] Native require loaded:', path); } else { await loadScript(path); console.log('[SDK] Loaded from:', path); } // 关键修复:加载后再次检查全局对象 ensureGlobalEnvironment(); initGravityEngine(); return; } catch (e) { console.warn('[SDK] Load failed:', path, e.message); } } console.error('[SDK] All paths failed'); handleSDKLoadFailure(); } function ensureGlobalEnvironment() { // 获取全局对象 const getGlobalObject = () => { if (typeof globalThis !== 'undefined') return globalThis; if (typeof global !== 'undefined') return global; if (typeof window !== 'undefined') return window; if (typeof self !== 'undefined') return self; return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 确保 self 在所有环境中都存在 if (typeof self === 'undefined') { console.warn('[GlobalFix] self is undefined, patching...'); Object.defineProperty(globalObj, 'self', { value: globalObj, writable: true, configurable: true, enumerable: true }); } // 确保其他关键全局对象存在 const requiredGlobals = ['window', 'global', 'globalThis', 'document', 'location']; requiredGlobals.forEach(name => { if (typeof globalObj[name] === 'undefined') { console.warn(`[GlobalFix] ${name} is undefined, patching...`); Object.defineProperty(globalObj, name, { value: globalObj, writable: true, configurable: true, enumerable: true }); } }); // 原生平台特殊处理 if (cc && cc.sys && cc.sys.isNative) { // 确保 location 对象存在 if (typeof location === 'undefined') { Object.defineProperty(globalObj, 'location', { value: { href: 'file://', protocol: 'file:', hostname: 'localhost' }, writable: false, configurable: false, enumerable: true }); } } } function loadScript(path) { return new Promise((resolve, reject) => { // 优先使用 Cocos 的加载系统 if (cc.assetManager?.loadScript) { cc.assetManager.loadScript(path, (err) => { if (err) { // 原生平台特殊处理 if (cc.sys.isNative) { console.warn('[SDK] Using native fallback for script loading'); try { // 原生平台直接执行脚本 const jsb = cc.sys.__globalAdapter; if (jsb && jsb.require) { jsb.require(path); return resolve(); } } catch (nativeError) { console.error('[SDK] Native require failed:', nativeError); } } reject(err); } else { resolve(); } }); return; } // 后备方案:直接创建 script 标签 try { const script = document.createElement('script'); script.src = path; script.onload = () => resolve(); script.onerror = () => reject(new Error(`Failed to load ${path}`)); document.head.appendChild(script); console.warn('[SDK] Using DOM fallback for script loading'); } catch (e) { reject(e); } }); } function initGravityEngine() { let GravityEngine = null; // 1. 尝试标准方式获取 if (typeof GravityEngine === 'function') { console.log('[SDK] GravityEngine found in local scope'); } // 2. 尝试从全局对象中查找 else if (typeof window.GravityEngine === 'function') { GravityEngine = window.GravityEngine; console.warn('[SDK] Found GravityEngine in window object'); } // 3. 尝试从其他全局对象中查找 else if (typeof global.GravityEngine === 'function') { GravityEngine = global.GravityEngine; console.warn('[SDK] Found GravityEngine in global object'); } // 4. 尝试从 self 对象中查找 else if (typeof self.GravityEngine === 'function') { GravityEngine = self.GravityEngine; console.warn('[SDK] Found GravityEngine in self object'); } // 5. 最后尝试从 globalThis 中查找 else if (typeof globalThis.GravityEngine === 'function') { GravityEngine = globalThis.GravityEngine; console.warn('[SDK] Found GravityEngine in globalThis object'); } else { console.error('[SDK] GravityEngine not found'); return; } try { // 使用您的 AppID 624768904 GravityEngine.init({ appId: '624768904', enableLog: true }); console.log('[SDK] GravityEngine initialized with AppID 624768904'); } catch (e) { console.error('[SDK] Init failed:', e); } } function handleSDKLoadFailure() { console.warn('[SDK] Using fallback analytics'); window.GravityEngine = { init: () => console.warn('SDK unavailable'), trackEvent: () => {} }; } // ====== 场景加载器 ====== async function loadStartScene() { try { // 加载主资源包 await new Promise((resolve) => { if (!cc.assetManager?.loadBundle) { console.warn('[Scene] AssetManager unavailable'); return resolve(); } cc.assetManager.loadBundle('main', (err) => { if (err) console.error('[Scene] Bundle load error:', err); resolve(); }); }); // 加载场景 if (cc.director?.loadScene) { cc.director.loadScene('start'); } else { throw new Error('Director unavailable'); } } catch (error) { console.error('[Scene] Load failed:', error); try { cc.director.loadScene('start'); } catch (e) { throw new Error('Fallback scene load failed'); } } } // ====== UI_Entry组件 ====== const { ccclass, property } = cc._decorator; @ccclass export default class UI_Entry extends cc.Component { @property(cc.ProgressBar) progress_loading = null; loginTimeoutHandler = null; onLoad() { EngineReady.safeAccess(() => { try { cc.director.getCollisionManager().enabled = true; this._show(); } catch (e) { console.error('[UI] onLoad error:', e); this.startLoadGame(); } }).catch(e => { console.error('[UI] Engine access error:', e); this.startLoadGame(); }); } onDestroy() { this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); } async _show() { this.progress_loading.progress = 0; // 平台SDK初始化 if (cc.sys.isBrowser) { try { await this.initYPSDK(); } catch (e) { console.error('[YPSDK] Init failed:', e); this.startLoadGame(); } } else { this.startLoadGame(); } // 登录超时保护 this.setLoginTimeout(); } setLoginTimeout() { if (cc.tween) { this.loginTimeoutHandler = cc.tween(this) .delay(10) .call(() => { console.warn('[Login] Timeout after 10s'); this.startLoadGame(); }) .start(); } else { setTimeout(() => this.startLoadGame(), 10000); } } async initYPSDK() { if (typeof YPSDK === 'undefined') { console.warn('[YPSDK] SDK unavailable'); return; } const config = { gameChannelList: { h5: { platformType: "h5", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" } } }; await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config); await YPSDK.login(); if (YPSDK.setLoginCallBack) { YPSDK.setLoginCallBack(success => { if (!success) return; // 取消超时 this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); // 初始化分析SDK if (r_GravityPlatform.default?.GA_Init) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); } this.startLoadGame(); }); } else { this.startLoadGame(); } } startLoadGame() { const tasks = [ this._loadGameConfig, this._loadRemoteConfig, this._loadExcelData, this._loadUserData, this._loadCommonBundle, this._loadMainBundle ].map(fn => fn.bind(this)); this.executeTasks(tasks, () => this._loadGame()); } executeTasks(tasks, finalCallback) { let completed = 0; const total = tasks.length; const runTask = async (index) => { if (index >= total) { finalCallback(); return; } try { await tasks[index](); completed++; this._setProgress(completed / total); runTask(index + 1); } catch (e) { console.error(`[Task ${index}] Failed:`, e); completed++; this._setProgress(completed / total); runTask(index + 1); // 继续执行后续任务 } }; runTask(0); } async _loadExcelData() { if (!r_ExcelLoader?.ExcelLoader?.loadAll) { console.warn('[Data] ExcelLoader unavailable'); return; } await r_ExcelLoader.ExcelLoader.loadAll(); console.log('[Data] Excel loaded'); } async _loadGameConfig() { if (!r_ResLoader.default?.loadRes) { console.warn('[Config] ResLoader unavailable'); return; } const jsonAsset = await r_ResLoader.default.loadRes( "resources", "config/GameConfig", cc.JsonAsset ); if (jsonAsset && r_GameConfig.default) { r_GameConfig.default.appConfig = jsonAsset.json; jsonAsset.decRef && jsonAsset.decRef(); console.log('[Config] Game config loaded'); } } async _loadRemoteConfig() { if (!r_GameConfig.default?.appConfig?.RemoteUrl) { console.warn('[Config] RemoteUrl not set'); return; } const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl; const remotePath = cc.path.join(remoteUrl, "ADConfig.json"); try { const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" }); if (remoteConfig?.json && r_GravityPlatform.default) { r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0]; r_GameConfig.default.adConfig = remoteConfig.json; console.log('[Config] Remote config loaded'); } } catch (e) { console.error('[Config] Remote load failed:', e); } } async _loadCommonBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common); console.log('[Bundle] Common loaded'); } catch (e) { console.error('[Bundle] Common load failed:', e); } } async _loadMainBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle); console.log('[Bundle] Main loaded'); } catch (e) { console.error('[Bundle] Main load failed:', e); } } async _loadUserData() { try { // 音频初始化 r_AudioManager.AudioMgr?.init(); // 全局配置 r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi(); // 网络检测 if (YPSDK?.Common?.curChannelData) { const platformType = YPSDK.Common.curChannelData.platformType; if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) { r_YpNetMag.YpNetMag?.failSever(() => { r_YpNetMag.YpNetMag.isFail = true; }); } } // 用户数据初始化 if (YPSDK?.Platform?.loginData) { await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData); } } catch (e) { console.error('[User] Load failed:', e); } } _loadGame() { try { const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName( r_Const_Common.GuideName.战斗背包 ); if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) { // 新玩家流程 r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.( r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1 ); r_GameDataManager.GameDataMgr?.ClearGameBagData(); r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; r_UIManager.default?.open( r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView ); } else { // 老玩家流程 r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); r_UIManager.default?.open( r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall ); } // 白名单检查 this.checkWhiteList(); } catch (e) { console.error('[Game] Load failed:', e); try { cc.director.loadScene('start'); } catch (sceneError) { console.error('[Game] Scene load failed:', sceneError); } } } async checkWhiteList() { try { if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return; const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`; if (r_HttpManager.HttpMgr?.requestData) { r_HttpManager.HttpMgr.requestData(res => { if (res?.data?.keyData === "true") { r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true; } }, url); } } catch (e) { console.error('[WhiteList] Check failed:', e); } } _setProgress(progress) { if (!this.progress_loading) return; this.progress_loading.progress = Math.max(0, Math.min(1, progress)); } } // ====== 启动游戏 ====== if (cc?.game?.run) { cc.game.run(() => { // 确保环境修复完成 ensureGlobalEnvironment(); gameMainEntry(); }); } else { setTimeout(() => { ensureGlobalEnvironment(); gameMainEntry(); }, 1000); } 针对上述问题 给我修改后的完整代码
07-16
// ====== 环境修复与全局对象安全 ====== (function() { // 确保全局对象存在 const getGlobalObject = () => { if (typeof globalThis !== 'undefined') return globalThis; if (typeof global !== 'undefined') return global; if (typeof window !== 'undefined') return window; if (typeof self !== 'undefined') return self; return Function('return this')() || {}; }; const globalObj = getGlobalObject(); // 修复全局变量 if (typeof global === 'undefined') global = globalObj; if (typeof self === 'undefined') self = globalObj; if (typeof globalThis === 'undefined') globalThis = globalObj; // 确保require函数存在(关键修复) if (typeof globalObj.require === 'undefined') { globalObj.require = function(module) { // 简单实现require功能 if (globalObj.__modules && globalObj.__modules[module]) { return globalObj.__modules[module]; } console.warn(`[RequireFallback] Module '${module}' not found`); return {}; }; console.log('[EnvFix] Created fallback require function'); } })(); // ====== 引擎初始化保护系统 ====== const EngineReady = (function() { let _promise = null; let _resolve = null; let _isReady = false; let _checkInterval = null; const safeCheckEngine = () => { // 引擎已初始化 if (cc && cc.game && cc.game._isEngineInited) { return true; } // 尝试监听初始化事件 if (cc && cc.game && cc.game.once) { const eventName = cc.game.EVENT_ENGINE_INITED || 'engine-inited'; cc.game.once(eventName, () => { _resolve && _resolve(); _isReady = true; _checkInterval && clearInterval(_checkInterval); }); return true; } return false; }; return { get isReady() { return _isReady; }, get promise() { return _promise; }, init() { if (!_promise) { _promise = new Promise(resolve => { _resolve = () => { _isReady = true; resolve(); _checkInterval && clearInterval(_checkInterval); }; // 首次检查 if (safeCheckEngine()) return; // 轮询检查 _checkInterval = setInterval(() => { safeCheckEngine() && _resolve(); }, 100); }); } return _promise; }, safeAccess(callback) { if (_isReady) { try { return callback(); } catch (e) { console.error('[EngineSafe] Error:', e); } } return _promise.then(callback).catch(e => { console.error('[EngineSafe] Async error:', e); }); } }; })(); EngineReady.init(); // ====== 游戏主入口 ====== async function gameMainEntry() { try { console.log('[Main] Waiting for engine initialization...'); await EngineReady.promise; console.log('[Main] Engine ready'); // 基本引擎配置 EngineReady.safeAccess(() => { if (cc.view) { cc.view.enableRetina(true); cc.view.resizeWithBrowserSize(true); cc.view.setDesignResolutionSize(960, 640, cc.ResolutionPolicy.SHOW_ALL); } }); // 加载SDK await loadGravityEngineSDK(); // 加载启动场景 await loadStartScene(); } catch (error) { console.error('[Main] Initialization failed:', error); try { cc.director.loadScene('start'); } catch (fallbackError) { displayErrorFallback('启动失败\n请重启应用'); } } } // 错误显示后备方案 function displayErrorFallback(message) { try { const errorDiv = document.createElement('div'); errorDiv.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: black; color: white; display: flex; justify-content: center; align-items: center; z-index: 9999; font: 24px Arial, sans-serif; text-align: center; white-space: pre-line; padding: 20px; `; errorDiv.textContent = message; document.body.appendChild(errorDiv); } catch (e) { console.error('[Fallback] Display failed:', e); } } // ====== SDK加载器 ====== async function loadGravityEngineSDK() { // 使用相对路径解决加载问题 const sdkPaths = [ './assets/_plugs/lib/gravityengine.mg.cocoscreator.min.js', '_plugs/lib/gravityengine.mg.cocoscreator.min.js', 'lib/gravityengine.mg.cocoscreator.min.js' ]; for (const path of sdkPaths) { try { await loadScript(path); console.log('[SDK] Loaded from:', path); initGravityEngine(); return; } catch (e) { console.warn('[SDK] Load failed:', path, e.message); } } console.error('[SDK] All paths failed'); handleSDKLoadFailure(); } function loadScript(path) { return new Promise((resolve, reject) => { // 优先使用Cocos的加载系统 if (cc.assetManager?.loadScript) { cc.assetManager.loadScript(path, (err) => { if (err) { reject(err); } else { resolve(); } }); return; } // 后备方案:直接创建script标签 try { const script = document.createElement('script'); script.src = path; script.onload = resolve; script.onerror = () => reject(new Error(`Failed to load ${path}`)); document.head.appendChild(script); console.warn('[SDK] Using DOM fallback for script loading'); } catch (e) { reject(e); } }); } function initGravityEngine() { if (typeof GravityEngine !== 'function') { console.error('[SDK] GravityEngine not found'); return; } try { // 使用您的AppID 624768904 GravityEngine.init({ appId: '624768904', enableLog: true }); console.log('[SDK] GravityEngine initialized with AppID 624768904'); } catch (e) { console.error('[SDK] Init failed:', e); } } function handleSDKLoadFailure() { console.warn('[SDK] Using fallback analytics'); window.GravityEngine = { init: () => console.warn('SDK unavailable'), trackEvent: () => {} }; } // ====== 场景加载器 ====== async function loadStartScene() { try { // 加载主资源包 await new Promise((resolve) => { if (!cc.assetManager?.loadBundle) { console.warn('[Scene] AssetManager unavailable'); return resolve(); } cc.assetManager.loadBundle('main', (err) => { if (err) console.error('[Scene] Bundle load error:', err); resolve(); }); }); // 加载场景 if (cc.director?.loadScene) { cc.director.loadScene('start'); } else { throw new Error('Director unavailable'); } } catch (error) { console.error('[Scene] Load failed:', error); try { cc.director.loadScene('start'); } catch (e) { throw new Error('Fallback scene load failed'); } } } // ====== UI_Entry组件 ====== const { ccclass, property } = cc._decorator; @ccclass export default class UI_Entry extends cc.Component { @property(cc.ProgressBar) progress_loading = null; loginTimeoutHandler = null; onLoad() { EngineReady.safeAccess(() => { try { cc.director.getCollisionManager().enabled = true; this._show(); } catch (e) { console.error('[UI] onLoad error:', e); this.startLoadGame(); } }).catch(e => { console.error('[UI] Engine access error:', e); this.startLoadGame(); }); } onDestroy() { this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); } async _show() { this.progress_loading.progress = 0; // 平台SDK初始化 if (cc.sys.isBrowser) { try { await this.initYPSDK(); } catch (e) { console.error('[YPSDK] Init failed:', e); this.startLoadGame(); } } else { this.startLoadGame(); } // 登录超时保护 this.setLoginTimeout(); } setLoginTimeout() { if (cc.tween) { this.loginTimeoutHandler = cc.tween(this) .delay(10) .call(() => { console.warn('[Login] Timeout after 10s'); this.startLoadGame(); }) .start(); } else { setTimeout(() => this.startLoadGame(), 10000); } } async initYPSDK() { if (typeof YPSDK === 'undefined') { console.warn('[YPSDK] SDK unavailable'); return; } const config = { gameChannelList: { h5: { platformType: "h5", version: "1.0.0" }, tt: { platformType: "tt", appId: "tt09297f94961f881b02" }, wx: { platformType: "wx", appId: "wx6baaaa27ab5186ff" } } }; await YPSDK.init(39, "https://platform-shop-dev.hanyougame.com", config); await YPSDK.login(); if (YPSDK.setLoginCallBack) { YPSDK.setLoginCallBack(success => { if (!success) return; // 取消超时 this.loginTimeoutHandler && cc.Tween.stop(this.loginTimeoutHandler); // 初始化分析SDK if (r_GravityPlatform.default?.GA_Init) { r_GravityPlatform.default.GA_Init(YPSDK.Platform.loginData.bindingId); } this.startLoadGame(); }); } else { this.startLoadGame(); } } startLoadGame() { const tasks = [ this._loadGameConfig, this._loadRemoteConfig, this._loadExcelData, this._loadUserData, this._loadCommonBundle, this._loadMainBundle ].map(fn => fn.bind(this)); this.executeTasks(tasks, () => this._loadGame()); } executeTasks(tasks, finalCallback) { let completed = 0; const total = tasks.length; const runTask = async (index) => { if (index >= total) { finalCallback(); return; } try { await tasks[index](); completed++; this._setProgress(completed / total); runTask(index + 1); } catch (e) { console.error(`[Task ${index}] Failed:`, e); completed++; this._setProgress(completed / total); runTask(index + 1); // 继续执行后续任务 } }; runTask(0); } async _loadExcelData() { if (!r_ExcelLoader?.ExcelLoader?.loadAll) { console.warn('[Data] ExcelLoader unavailable'); return; } await r_ExcelLoader.ExcelLoader.loadAll(); console.log('[Data] Excel loaded'); } async _loadGameConfig() { if (!r_ResLoader.default?.loadRes) { console.warn('[Config] ResLoader unavailable'); return; } const jsonAsset = await r_ResLoader.default.loadRes( "resources", "config/GameConfig", cc.JsonAsset ); if (jsonAsset && r_GameConfig.default) { r_GameConfig.default.appConfig = jsonAsset.json; jsonAsset.decRef && jsonAsset.decRef(); console.log('[Config] Game config loaded'); } } async _loadRemoteConfig() { if (!r_GameConfig.default?.appConfig?.RemoteUrl) { console.warn('[Config] RemoteUrl not set'); return; } const remoteUrl = r_GameConfig.default.appConfig.RemoteUrl; const remotePath = cc.path.join(remoteUrl, "ADConfig.json"); try { const remoteConfig = await r_ResLoader.default.loadRemote(remotePath, { ext: ".json" }); if (remoteConfig?.json && r_GravityPlatform.default) { r_GravityPlatform.default.videoId = remoteConfig.json.ADUnitId[0]; r_GameConfig.default.adConfig = remoteConfig.json; console.log('[Config] Remote config loaded'); } } catch (e) { console.error('[Config] Remote load failed:', e); } } async _loadCommonBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.BundleNames.Common); console.log('[Bundle] Common loaded'); } catch (e) { console.error('[Bundle] Common load failed:', e); } } async _loadMainBundle() { if (!r_ResLoader.default?.loadBundle) { console.warn('[Bundle] ResLoader unavailable'); return; } try { await r_ResLoader.default.loadBundle(r_BundleConfig.MainGameBundle); console.log('[Bundle] Main loaded'); } catch (e) { console.error('[Bundle] Main load failed:', e); } } async _loadUserData() { try { // 音频初始化 r_AudioManager.AudioMgr?.init(); // 全局配置 r_GameGlobalVariable.GameGlobalVariable?.initPeiZhi(); // 网络检测 if (YPSDK?.Common?.curChannelData) { const platformType = YPSDK.Common.curChannelData.platformType; if (platformType === YPSDK.GamePlatformType.WX || platformType === YPSDK.GamePlatformType.TT) { r_YpNetMag.YpNetMag?.failSever(() => { r_YpNetMag.YpNetMag.isFail = true; }); } } // 用户数据初始化 if (YPSDK?.Platform?.loginData) { await r_YpNetMag.YpNetMag?.initServer(YPSDK.Platform.loginData); } } catch (e) { console.error('[User] Load failed:', e); } } _loadGame() { try { const guideIndex = r_PlayerDataManager.PlayerDataMgr.GetGuideIndexByTaskName( r_Const_Common.GuideName.战斗背包 ); if (guideIndex !== r_Const_Common.GameBagGuideIndex.引导完结) { // 新玩家流程 r_PlayerDataManager.PlayerDataMgr.GMSetGuideIndex?.( r_Const_Common.GuideName.战斗背包, r_Const_Common.GameBagGuideIndex.引导初始1 ); r_GameDataManager.GameDataMgr?.ClearGameBagData(); r_GameGlobalVariable.GameGlobalVariable.nowlevel = 1; r_UIManager.default?.open( r_BundleConfig.BundleNames.Game, r_UIConfig_Game.UIView_Game.UI_GameView ); } else { // 老玩家流程 r_EventManager.EventMgr?.dispatchEvent(r_EvenType.EVENT_TYPE.Game_Load_View, true); r_UIManager.default?.open( r_BundleConfig.BundleNames.Home, r_UIConfig_Home.UIView_Home.UI_Hall ); } // 白名单检查 this.checkWhiteList(); } catch (e) { console.error('[Game] Load failed:', e); try { cc.director.loadScene('start'); } catch (sceneError) { console.error('[Game] Scene load failed:', sceneError); } } } async checkWhiteList() { try { if (!YPSDK?.Platform?.loginData || !YPSDK.platformUrl) return; const url = `${YPSDK.platformUrl}/User/GetCfgData?userId=${YPSDK.Platform.loginData.userUid}&keyId=NoVideo`; if (r_HttpManager.HttpMgr?.requestData) { r_HttpManager.HttpMgr.requestData(res => { if (res?.data?.keyData === "true") { r_PlayerDataManager.PlayerDataMgr.WHITE_NAME_NO_VIDEO = true; } }, url); } } catch (e) { console.error('[WhiteList] Check failed:', e); } } _setProgress(progress) { if (!this.progress_loading) return; this.progress_loading.progress = Math.max(0, Math.min(1, progress)); } } // ====== 启动游戏 ====== if (cc?.game?.run) { cc.game.run(gameMainEntry); } else { setTimeout(gameMainEntry, 1000); } 我的代码你已经给我修改过了 依旧出现这个错误
07-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值