// var window.mode_env = 'development'; window.mode_env = 'production'; let API_URL=window.themeConfig.api; // if ( // window.location.href.indexOf('localhost') >= 0 || // window.location.href.indexOf('192.168.1.') >= 0 || // window.location.href.indexOf('192.168.11.') >= 0 || // window.location.href.indexOf('10.10.100.') >= 0 || // window.location.href.indexOf('bigwinga.me') >= 0 || // window.location.href.indexOf('thekongfu.com') >= 0 || // window.location.href.indexOf('kysdkllc.com') >= 0 // ) { // window.mode_env = 'development'; // } else { // window.mode_env = 'production'; // } // 初始化 渠道信息 var SingletonChannelInfo = (function () { // 存储单例实例的变量 var instance; // 初始化实例的函数 function init(newh2, newh3, newh4) { var h2 = newh2 || 'h5'; var h3 = newh3 || 'web'; var h4 = newh4 || ''; return { // 公有方法和属性 h2, h3, h4 }; } return { // 获取单例的实例的方法 getInstance: function (...args) { if (!instance && args.length > 0) { instance = init(...args); // 如果实例不存在,创建它 } if (!instance && args.length === 0) { instance = init(); } return instance; // 返回单例实例 } }; })(); // function getCookie(key) { // const cookie = document.cookie; // const cookieArr = cookie.split(";"); // const cookieObj = {}; // cookieArr.forEach((item) => { // const [key, value] = item.split("="); // cookieObj[key.trim()] = value; // }); // return key ? cookieObj[key] : cookieObj; // } window.hasFixexpire = false; function getCookie(key) { const cookie = document.cookie; const cookieArr = cookie.split(';'); const cookieObj = {}; cookieArr.forEach(item => { const [k, v] = item.split('='); const trimmedKey = k ? k.trim() : ''; const trimmedValue = v ? v.trim() : ''; if (trimmedKey && trimmedValue) cookieObj[trimmedKey] = trimmedValue; }); if (!window.hasFixexpire) { if (cookieObj['winus_uuid']) { setCookie('winus_uuid', cookieObj['winus_uuid']); } if (cookieObj['us_h5_sourceurl_key']) { setCookie('us_h5_sourceurl_key', cookieObj['us_h5_sourceurl_key']); } window.hasFixexpire = true; } return key ? cookieObj[key] : cookieObj; } function setCookie(key, value, expires = 365 * 24 * 60 * 60 * 1000) { const date = new Date(); date.setTime(date.getTime() + expires); document.cookie = `${key}=${value};path=/;domain=.${window.location.hostname.split('.').slice(-2).join('.')};expires=${date.toUTCString()};SameSite=None;Secure;`; } function isInApk() { if (!window.android) return false; if (!window.android?.getDeviceID || !window.android?.saveUserID) return false; return true; } function getSubscriptionInfo() { var installed = isPwaInstall(); var cacheKey = 'submit_subscription_' + udatadict.channel + '_' + udatadict.userid + '_' + installed; return localStorage.getItem(cacheKey) === '1'; } function getSafeReturnUrl(value) { if (typeof value !== 'string' || value.trim() === '') return ''; try { var url = new URL(value, window.location.href); return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : ''; } catch (error) { return ''; } } function getIsPostData() { var installed = isPwaInstall(); var cacheKey = 'submit_subscription_post_' + udatadict.channel + '_' + udatadict.userid + '_' + installed; return localStorage.getItem(cacheKey) === '1'; } function setIsPostData() { var installed = isPwaInstall(); var cacheKey = 'submit_subscription_post_' + udatadict.channel + '_' + udatadict.userid + '_' + installed; localStorage.setItem(cacheKey, '1'); } // 获取全局唯一标识 var getUniqueID = (function () { // 缓存全局唯一标识 let __global_unique_ID; // 缓存 promise 避免多次执行 let promiseInProgress = null; function resolveUniqueID(resolve, value) { let uniqueID = value; if (!uniqueID) { try { uniqueID = getLocalUUID(); } catch (error) { errorpushlog('Failed to create local unique ID:', error); } } if (uniqueID) { __global_unique_ID = uniqueID; try { setCookie('winus_uuid', uniqueID, 604800000); } catch (error) { errorpushlog('Failed to cache unique ID:', error); } } resolve(uniqueID || ''); } return function () { if (__global_unique_ID) { return Promise.resolve(__global_unique_ID); } // 如果已经有全局唯一标识, 直接返回 var cookie_md5_val = getCookie('winus_uuid'); // if(!cookie_md5_val){ // cookie_md5_val=getLocalUUID(); // if(cookie_md5_val){ // setCookie('winus_uuid', cookie_md5_val, 604800000); // } // } if (cookie_md5_val) { __global_unique_ID = cookie_md5_val; return Promise.resolve(__global_unique_ID); } if (promiseInProgress) { return promiseInProgress; } if (isInApk()) { // apk 环境下, 直接返回 promiseInProgress = new Promise(resolve => { let completed = false; const finish = deviceId => { if (completed) return; completed = true; clearTimeout(timeoutId); resolveUniqueID(resolve, deviceId); }; const timeoutId = setTimeout(() => finish(''), 5000); try { // IPA 环境 if (window?.android?.isIpa) { // 确保回调函数在调用 getDeviceID 之前就绑定好 window.android.deviceIdCallback = function (deviceId) { finish(deviceId); }; window.android.getDeviceID?.(); return; } // 普通 APK 环境 const deviceId = window?.android?.getDeviceID?.(); finish(deviceId); } catch (error) { errorpushlog('Failed to read native device ID:', error); finish(''); } }); return promiseInProgress; } promiseInProgress = new Promise(function (resolve) { var iframe = document.createElement('iframe'); iframe.src = window.location.protocol + '//cen.greatus777.com/storage'; // iframe.src = window.location.protocol + '//' + 'dev.winus777.com' + '/storage'; var iframeOrigin = new URL(iframe.src).origin; var timeoutId = null; var completed = false; function cleanup() { if (timeoutId) clearTimeout(timeoutId); window.removeEventListener('message', messageHandler); if (iframe.parentNode) iframe.parentNode.removeChild(iframe); } function finish(value) { if (completed) return; completed = true; cleanup(); resolveUniqueID(resolve, value); } iframe.style.display = 'none'; iframe.addEventListener('load', function () { iframe.contentWindow?.postMessage('getUniqueID', iframeOrigin); }, { once: true }); iframe.addEventListener('error', function () { finish(''); }, { once: true }); function messageHandler(event) { if (event.origin !== iframeOrigin || event.source !== iframe.contentWindow) return; const uniqueID = event.data && typeof event.data === 'object' ? event.data.md5val : ''; if (uniqueID) finish(uniqueID); } // 监听 iframe 的消息 window.addEventListener('message', messageHandler); document.body.appendChild(iframe); timeoutId = setTimeout(function () { finish(''); }, 8000); }); return promiseInProgress; }; })(); /** * 上报订阅信息 * @param {*} data * { * userid: 1, // 用户ID * result: 1, // 1 接受 2未接受 3 不支持 4 拒绝 * machineserial 机器码 * ish5 0:app(w2a),1:h5(pwa) * p_source * } */ function uploadSubscription(data) { if (+data.ish5 !== 0 && +data.ish5 !== 1) return; const ajax = new XMLHttpRequest(); const callback = data.callback; ajax.open('POST', API_URL+"/api/upload_subscribe_state", true); ajax.setRequestHeader('Content-Type', 'application/json'); ajax.onreadystatechange = function () { if (ajax.readyState === 4 && ajax.status === 200) { setIsPostData(); } callback && callback(); }; ajax.onerror = function () { callback && callback(); }; ajax.send(JSON.stringify(data)); } function isIOS() { try { let u = navigator.userAgent; let isIOS = false; // 检查是否包含 iPhone, iPad, iPod 或 Mac OS X (通常Safari在iOS上运行) if (/(iPhone|iPad|iPod|iOS)/i.test(u)) { isIOS = true; } // 排除 Android,避免误判 if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) { isIOS = false; } return isIOS } catch (t) { return false } } function openUrlUseSafari(url = "", isNewTab = true, isBFP = true) { if (url == null || url === "") url = window.location.href; if (window.BFP != null && window.BFP !== "" && isBFP) { if (url.indexOf("?") === -1) url += "?bfp=" + window.BFP; else url += "&bfp=" + window.BFP; } if (isIOS()) { const safariUrl = url.startsWith('https') ? url.replace('https://', 'x-safari-https://') : url.replace('http://', 'x-safari-https://'); if (isNewTab) { window.open(safariUrl, '_blank', 'noopener,noreferrer'); } else { window.location.href = safariUrl; } } } function openChrome() { var url = window.location.href; if (isIOS()) { let r = "googlechromes://" + url.replace(/^https?:\/\//, ""); window.open(r, "_blank", "noopener,noreferrer"); } else { url = url.replace('https://', ''); url = url.replace('http://', ''); var newLink = 'intent://' + url + '#Intent;scheme=https;action=android.intent.action.VIEW;component=com.android.chrome;end'; var a = document.getElementById('pwaIFrame'); if (!a) { a = document.createElement('iframe'); a.id = 'pwaIFrame'; a.style.width = '0'; a.style.height = '0'; a.style.opacity = '0'; a.name = 'pwaIFrame'; document.body.appendChild(a); } a.src = newLink; } setTimeout(() => { if (!document.hidden) { uploadSubscription({ userid: udatadict.userid || '', result: 3, machineserial: udatadict.machineserial, ish5: 1, p_source: udatadict.channel }); } }, 1000); document.body.removeEventListener('click', openChrome); } // 判断是否在 chrome 浏览器中 function isInChromeBrowser() { return /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); } var pushOfFingerprint = ''; var udatadict = {}; var pushLogOpen = true; function pushmlog(...args) { if (pushLogOpen) { console.log('Push log:', ...args); } } function errorpushlog(...args) { if (true) { console.error('Push error log:', ...args); } } // 将URL Base64编码的字符串转换为Uint8Array function urlBase64ToUint8Array(base64String) { var padding = '='.repeat((4 - (base64String.length % 4)) % 4); var base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); var rawData = window.atob(base64); var outputArray = new Uint8Array(rawData.length); for (var i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; } // 判断是否在PWA模式下运行 function isPwaInstall() { if ( window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone || document.referrer.includes('android-app://') ) { return 1; } else { return 0; } } // 获取平台 function getPlatform() { var ua = navigator.userAgent; if (ua.match(/Android/i)) { return 'Android'; } else if (ua.match(/iPhone|iPad|iPod/i)) { return 'iOS'; } else { return 'Other'; } } // 将订阅信息发送到服务器 function submitSubscription(subscription, channel, userid) { // 注意落地页和游戏内的指纹算法保持一致!!! var fingerprint = pushOfFingerprint; var website = window.location.href; // 发送订阅信息到服务器 // xmlhttprequest var xhr = new XMLHttpRequest(); // 墨西哥订阅地址 if (window.mode_env === 'development') { xhr.open('POST', API_URL + '/api/push_subscribe', true); } else { xhr.open('POST', API_URL + '/api/push_subscribe', true); } xhr.setRequestHeader('Content-Type', 'application/json'); var contentData = { fingerprint: fingerprint, userid: userid, // 如果有用户登录,可以传用户ID subscibe_info: JSON.stringify(subscription), channel: channel, web_site: website, platform: getPlatform(), installed: isPwaInstall() }; xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { pushmlog('Subscription info sent to server:', xhr.responseText); var installed = isPwaInstall(); var cacheKey = 'submit_subscription_' + channel + '_' + userid + '_' + installed; localStorage.setItem(cacheKey, '1'); } }; xhr.onerror = function () { errorpushlog('Failed to send subscription info'); }; xhr.send(JSON.stringify(contentData)); } // 埋点日志 function recordEvent(eventName, channel, remark, userid) { var info = SingletonChannelInfo.getInstance(); var h2 = info.h2; var h3 = info.h3; var h4 = info.h4 || channel; var host = 'us_' + h2 + '_' + h3 + '_' + h4; var url = API_URL + '/api/weblog?host=' + host + '&act=' + eventName + '&remark=' + remark + '&orderid=' + userid; var xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.send(); } // 请求用户授权订阅推送通知 function requestNotificationPermission(registration, channel, userid, machineserial, ish5) { // 检查浏览器是否支持Notification API if ('Notification' in window) { // 请求授权 Notification.requestPermission().then(function (permission) { if (permission === 'granted') { pushmlog('User has authorized push notifications'); recordEvent('push_permission', channel, 'allow', userid); // 注册Service Worker return registration.pushManager .subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array( 'BEKE0qlrGMp-XyUHppeFMscDiJg-sL98jr4b51glbvicHnD69oNZ9JiLHKIQ9_3K0ImSZlo0Ggw-RE3FxYOUwJo' ) }) .then(function (subscription) { var saveSubScription = JSON.stringify(subscription); localStorage.setItem('subscription', saveSubScription); pushmlog('User has subscribed to push notifications:', subscription); // 将订阅信息发送到服务器 submitSubscription(subscription, channel, userid); uploadSubscription({ userid: userid || '', result: 1, machineserial, ish5, p_source: channel, callback: function () { if (+ish5 === 1 || +ish5 === 0) { // 如果是H5游戏, 则打开网址 if (+ish5 === 1) { if (udatadict.returnurl) { setTimeout(() => { window.location.href = udatadict.returnurl; }, 1000); } } else { // 打开游戏 const div = document.createElement('div'); div.style = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 9999;'; div.innerHTML = `