UNPKG

share-light

Version:
1,285 lines (1,270 loc) 57.2 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.shareLightSDK = {})); })(this, (function (exports) { 'use strict'; /** * 复制到剪切板 * * @param {string} text 待复制的文本 * @returns {Promise<void>} * @example * * ```ts * clipboardMp('stupid').then(() => {}); * ``` */ function clipboardWeb(text) { return new Promise(function (resolve, reject) { var pasteText = document.getElementById('#clipboard'); pasteText === null || pasteText === void 0 ? void 0 : pasteText.remove(); var textarea = document.createElement('textarea'); textarea.id = '#clipboard'; textarea.style.position = 'fixed'; textarea.style.top = '-9999px'; textarea.style.zIndex = '-9999'; document.body.appendChild(textarea); textarea.value = "".concat(text); textarea.select(); textarea.setSelectionRange(0, textarea.value.length); var result = document.execCommand('Copy', false); textarea.blur(); if (result) { resolve(); } else { reject(); } }); } var addScript = function addScript(script) { var _a; // Get the first script element, we're just going to use it // as a reference for where to insert ours. Do NOT try to do // this just once at the top and then re-use the same script // as a reference later. Some weird loaders *remove* script // elements after the browser has executed their contents, // so the same reference might not have a parentNode later. var firstScript = document.getElementsByTagName('script')[0]; // Append the script to the DOM, triggering execution. (_a = firstScript === null || firstScript === void 0 ? void 0 : firstScript.parentNode) === null || _a === void 0 ? void 0 : _a.insertBefore(script, firstScript); }; /** * 以 Callback 的方式加载 js 文件 * @param {String} src js文件路径 * @param {Function|Object} callback 加载回调 * @param {String} charset 指定js的字符集 * @param {Object} context Callback context */ var loader = function loader(src, callback, charset, context) { if (charset === void 0) { charset = 'utf-8'; } if (context === void 0) { context = null; } var setup; if (callback && typeof callback !== 'function') { context = callback.context || context; setup = callback.setup; callback = callback.callback; } var done = false; var err; var privateCleanup; // _must_ be set below. /** * Final handler for error or completion. * * **Note**: Will only be called _once_. * * @returns {void} */ var privateFinish = function privateFinish() { // Only call once. if (done) { return; } done = true; // Internal cleanup. privateCleanup === null || privateCleanup === void 0 ? void 0 : privateCleanup(); // Callback. if (callback) { callback.call(context, err); } }; /** * Error handler * * @returns {void} */ var privateError = function privateError() { err = new Error(src || 'EMPTY'); privateFinish(); }; var curScript = document.querySelector("script[src=\"".concat(src, "\"]")); if (curScript) { var tc_1 = setInterval(function () { if (curScript.isready) { // 判断js加载完成 privateFinish(); clearInterval(tc_1); } }, 20); } else { var script_1 = document.createElement('script'); script_1.isready = false; if (script_1.readyState && !('async' in script_1)) { var isReady_1 = { loaded: true, complete: true }; var inserted_1 = false; // Clear out listeners, state. privateCleanup = function privateCleanup() { script_1.onreadystatechange = null; script_1.onerror = null; }; // Attach the handler before setting src, otherwise we might // miss events (consider that IE could fire them synchronously // upon setting src, for example). script_1.onreadystatechange = function () { var firstState = script_1.readyState; // Protect against any errors from state change randomness. if (err) { return; } if (!inserted_1 && isReady_1[firstState]) { inserted_1 = true; // Append to DOM. addScript(script_1); } if (firstState === 'loaded') { // The act of accessing the property should change the script's // `readyState`. // // And, oh yeah, this hack is so hacky-ish we need the following // eslint-disable-next-line @typescript-eslint/no-unused-expressions script_1.children; if (script_1.readyState === 'loading') { // State transitions indicate we've hit the load error. // // **Note**: We are not intending to _return_ a value, just have // a shorter short-circuit code path here. return privateError(); } } // It's possible for readyState to be "complete" immediately // after we insert (and execute) the script in the branch // above. So check readyState again here and react without // waiting for another onreadystatechange. if (script_1.readyState === 'complete') { script_1.isready = true; privateFinish(); } }; // Onerror handler _may_ work here. script_1.onerror = privateError; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script_1); } // This triggers a request for the script, but its contents won't // be executed until we append it to the DOM. script_1.src = src; // In some cases, the readyState is already "loaded" immediately // after setting src. It's a lie! Don't append to the DOM until // the onreadystatechange event says so. } else { // This section is for modern browsers, including IE10+. // Clear out listeners. privateCleanup = function privateCleanup() { script_1.onload = null; script_1.onerror = null; }; script_1.onerror = privateError; script_1.onload = function () { script_1.isready = true; privateFinish(); }; script_1.async = true; script_1.charset = charset || 'utf-8'; // call the setup callback to mutate the script tag if (setup) { setup.call(context, script_1); } script_1.src = src; // Append to DOM. addScript(script_1); } } }; /** * 解决图片跨域问题,将网络图片URL转为base64 URL。 * @param {string} src 网络图片URL * @returns {Promise} Promise对象返回base64 URL * * @example * Dom2Image.urlToBase64("http://test.com/image.png").then(url=>{}); */ function urlToBase64(src) { return new Promise(function (resolve) { var img = new Image(); // 兼容不同格式的url,加随机数防止走缓存 if (src.indexOf('?') === -1) { src = "".concat(src, "?t=").concat(new Date().getTime()); } else { src = "".concat(src, "&t=").concat(new Date().getTime()); } img.setAttribute('crossOrigin', 'anonymous'); img.src = src; img.onload = function () { var canvas = convertImageToCanvas(img); var url = canvas.toDataURL('image/png'); resolve(url); }; img.onerror = function () { resolve(''); }; }); } /** * image url转canvas * @param image {Image} 图片src * @returns canvas */ function convertImageToCanvas(image) { var _a; var canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; canvas.dpi = window.devicePixelRatio; (_a = canvas.getContext('2d')) === null || _a === void 0 ? void 0 : _a.drawImage(image, 0, 0, image.width, image.height); return canvas; } /** * 获取UA * @private * @returns {string} ua */ function getRealUA() { return (navigator.userAgent || '').toLowerCase(); } /** * 检查是否是ios环境 * @returns {boolean} 是否是ios环境 * * @example * * checkUAIsIOS() * * // => true * */ function checkUAIsIOS() { var realUA = getRealUA(); return /iphone|ipod|ipad|Mac OS X/i.test(realUA) || !!realUA.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); } /** * 获取useragent类型 * @returns {object} useragent的map * @example * * getEnvUAType() * * // => * { * isWeixin: false, * isWorkWeixin: false, * isQQ: false, * isPvpApp: false, * isTipApp: false, * isAndroid: false, * isIos: true, * isIOS: true, * isMsdk: false, * isMsdkV5: false, * isSlugSdk: false, * isInGame: false, * isGHelper: false, * isGHelper20004: false, * isMiniProgram: false, * isLolApp: false, * isWindowsPhone: false, * isSymbian: false, * isPc: true, * }; * */ function getEnvUAType() { var ua = getRealUA(); var isWeixin = ua.indexOf('micromessenger') !== -1; var isWorkWeixin = ua.indexOf('wxwork') !== -1; var isQQ = ua.indexOf(' qq/') !== -1; var isPvpApp = ua.indexOf(' igameapp/') !== -1; var isTipApp = ua.indexOf(' gamelife/') !== -1; var isAndroid = ua.indexOf('android') !== -1; var isIos = checkUAIsIOS(); var isIOS = isIos; var isMsdk = ua.indexOf(' msdk/') !== -1; // msdk var isMsdkX = ua.indexOf(' webviewx msdk/') !== -1; // 嵌入式msdk浏览器 var isMsdkV5 = ua.indexOf(' msdk/5') !== -1; // msdk V5 var isSlugSdk = ua.indexOf('ingame') !== -1; // 微社区sdk var isInGame = isMsdk || isSlugSdk; // 是否游戏内 var isGHelper = ua.indexOf('gamehelper') !== -1; var isGHelper20004 = ua.indexOf('gamehelper_20004') !== -1; var isMiniProgram = ua.indexOf('miniprogram') !== -1 || typeof window !== 'undefined' // eslint-disable-next-line no-underscore-dangle && window.__wxjs_environment === 'miniprogram'; var isLolApp = ua.indexOf('lolapp') !== -1; // 掌上英雄联盟app var isWindowsPhone = /(?:Windows Phone)/.test(ua); var isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone; var isPc = !ua.match(/(phone|pad|pod|iphone|ipod|ios|ipad|android|mobile|blackberry|iemobile|mqqbrowser|juc|fennec|wosbrowser|browserng|webos|symbian|windows phone)/i); return { isWeixin: isWeixin, isWorkWeixin: isWorkWeixin, isQQ: isQQ, isPvpApp: isPvpApp, isTipApp: isTipApp, isAndroid: isAndroid, isIos: isIos, isIOS: isIOS, isMsdk: isMsdk, isMsdkX: isMsdkX, isMsdkV5: isMsdkV5, isSlugSdk: isSlugSdk, isInGame: isInGame, isGHelper: isGHelper, isGHelper20004: isGHelper20004, isMiniProgram: isMiniProgram, isLolApp: isLolApp, isWindowsPhone: isWindowsPhone, isSymbian: isSymbian, isPc: isPc }; } /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /** * 根据传入的参数,移除原来的所有参数,根据传入的 keepParamsObj 进行重新拼接地址,以 hash 模式返回 * @param {string} url 地址 * @param {object} keepParamsObj 参数对象 * @returns 只有传入参数的地址 * @example * const url1 = formatUrlParams('http://www.test.com?a=1&b=2&c=3', { e: 5 }); // http://www.test.com/#/?e=5 * const url2 = formatUrlParams('http://www.test.com?a=1&b=2&c=3#/detail?d=4', { f: 5 }); // http://www.test.com/#/detail?f=5 */ function formatUrlParams(url, keepParamsObj, forceHistoryMode) { if (url === void 0) { url = ''; } if (keepParamsObj === void 0) { keepParamsObj = {}; } // 参数校验 var keepKeyArr = Object.keys(keepParamsObj); if (!url) { return url; } // 转换地址参数为字符串 var paramsStr = keepKeyArr.reduce(function (str, key) { var value = keepParamsObj[key]; var item = "".concat(key, "=").concat(value); if (str !== '') { return "".concat(str, "&").concat(item); } return item; }, ''); // 通过 HTMLAnchorElement 规范链接格式 var anchorElement = document.createElement('a') || {}; anchorElement.href = url; var _a = anchorElement.origin, origin = _a === void 0 ? '' : _a, _b = anchorElement.pathname, pathname = _b === void 0 ? '' : _b, _c = anchorElement.hash, hash = _c === void 0 ? '' : _c; if (!origin) { return url; } // 获取 router 的目标 path var matchRes = hash.match(/^#([^?]*)/); var routeName = matchRes === null || matchRes === void 0 ? void 0 : matchRes[1]; // 重新拼接链接,判断采用 history 或 hash 模式返回 var routerPath = ''; // hash 模式拼上 if (!forceHistoryMode) { var isHistory = url.includes('?') && !url.includes('#'); // forceHistoryMode未传的history模式,默认加上hash if (!(forceHistoryMode !== false && isHistory)) { routerPath = "#".concat(routeName || '/'); } } var formatUrl = "".concat(origin).concat(pathname).concat(routerPath, "?").concat(paramsStr); return formatUrl; } /** * 提取链接参数,兼容hash模式和history模式,以及拼接异常情况 * @param {string} [url=''] 地址 * @param {string} [key=''] 可选,若不为空,则提取返回该key对应的参数值 * @returns 地址参数对象,或者是指定参数值 * @example * const url = 'https://igame.qq.com?name=mike&age=18#/index?from=china&home=china' * const params = resolveUrlParams(url); // { from: 'china', home: 'china', name: 'mike', age: 18 } * const paramsAge = resolveUrlParams(url, 'age'); // 18 */ function resolveUrlParams(url, key) { if (url === void 0) { url = ''; } if (key === void 0) { key = ''; } if (!url) return key ? undefined : {}; // 解码 var link = url; // 提取从第一个问号开始后的字符串内容(含问号) link = link.substring(url.indexOf('?')); // 正则匹配方式提取键值对 // eslint-disable-next-line no-useless-escape var matchList = link.match(/(\?|&)([^\?&]*=[^\?&#]*)/g); if (!matchList) { return key ? undefined : {}; } // 提取多个键值对 var params = {}; var kvList = matchList.map(function (item) { return item.replace(/(\?|&)/g, ''); }); // 移除 ? 或 & 前缀 kvList.forEach(function (kv) { var _a = kv.split('='), key = _a[0], value = _a[1]; if (value) { // 有值时,才记录 params[key] = value; } }); return key ? params[key] : params; } function simpleRemoveUrlParams(url, removeKeyArr) { if (url === void 0) { url = ''; } if (removeKeyArr === void 0) { removeKeyArr = []; } if (!url.includes('?') || !removeKeyArr.length) { return url; } var list = url.split('?'); var query = list[1].split('&').reduce(function (acc, item) { var _a; var list = item.split('='); return __assign(__assign({}, acc), (_a = {}, _a[list[0]] = list[1], _a)); }, {}); var queryStr = Object.keys(query).filter(function (item) { return !removeKeyArr.includes(item); }).map(function (item) { return "".concat(item, "=").concat(query[item]); }).join('&'); if (!queryStr) { return list[0]; } return "".concat(list[0], "?").concat(queryStr); } function isSimpleUrl(url) { if (url === void 0) { url = ''; } return url.indexOf('?') === url.lastIndexOf('?'); } /** * @export removeUrlParams * @description 移除参数 * @param {string} url 地址 * @param {string} removeKeyArr 待移除的参数名集合 * @returns 重新拼接的地址 * @example * const url = removeUrlParams('http://www.test.com/#/detail?a=1&b=2&c=3', ['a', 'b']); // 'http://www.test.com/#/detail?c=3' * const url2 = removeUrlParams('http://www.test.com?d=4&f=6#/detail?a=1&b=2&c=3', ['a', 'd']); // 'http://www.test.com/#/detail?b=2&c=3&f=6' */ function removeUrlParams(url, removeKeyArr, forceHistoryMode) { if (url === void 0) { url = ''; } if (isSimpleUrl(url)) { return simpleRemoveUrlParams(url, removeKeyArr); } // 获取链接上的所有参数 var urlParamsObj = resolveUrlParams(url); // 移除指定的key集合 var keepParamsObj = {}; Object.keys(urlParamsObj).forEach(function (key) { if (!removeKeyArr.includes(key)) { keepParamsObj[key] = urlParamsObj[key]; } }); // 根据移除后的参数集合,重新拼接地址 return formatUrlParams(url, keepParamsObj, forceHistoryMode); } const DEFAULT_SHARE_ICON = 'http://ossweb-img.qq.com/images/pmd/igameapp/logo/log_igame_3.0.png'; const DEFAULT_TIP_MAP = { copyTextSuccess: '复制链接成功,快去粘贴吧!', copyTextFail: '该浏览器不支持自动复制', dialogTitle: '温馨提示', dialogMessage: '请复制链接到微信或手机QQ内打开参与活动', dialogConfirmButton: '我知道了', }; const SHARE_TYPE_MAP = { Wechat: 1, Timeline: 2, QQ: 3, QZone: 4, }; let shareObject = { title: '', desc: '', icon: '', link: '', callback: _shareType => ({}), path: '', type: '', miniprogram_link: '', tipMap: DEFAULT_TIP_MAP, }; let isWzydShare = false; // 显示王者营地样式的分享提示浮层 let wzydShareText = '点击“...”分享链接'; function getEnv() { const ua = navigator.userAgent.toLowerCase(); const env = Object.assign({ ua }, getEnvUAType()); return env; } const shareUiObj = {}; shareUiObj.initCommShareUI = function (callback) { var _a, _b, _c, _d, _e, _f; const idObjectStyle = document.getElementById('div_share_ui_style'); if (idObjectStyle != null) { (_a = idObjectStyle.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(idObjectStyle); } const styleNode = document.createElement('style'); styleNode.id = 'div_share_ui_style'; styleNode.type = 'text/css'; styleNode.innerHTML = ` .share-dialog-login{ padding:30px 20px; position:fixed; left:0; right:0; bottom:0;background:#222222; z-index:2001}\ .share-choose-login {width:100%;margin:20px auto 0;text-align: center;font-size:0;}\ .share-choose-login a {display:inline-block;vertical-align:middle;width:25%;}\ .share-type{ width:45px; height:45px; display:block; margin:0 auto; }\ .share-type-1{background:url(//game.gtimg.cn/images/sy/2016/miniweb/ingame/commsrc/shareicon.png) no-repeat;background-size:auto 100%;}\ .share-type-2{background:url(//game.gtimg.cn/images/sy/2016/miniweb/ingame/commsrc/shareicon.png) -45px 0 no-repeat;background-size:auto 100%;}\ .share-type-3{background:url(//game.gtimg.cn/images/sy/2016/miniweb/ingame/commsrc/shareicon.png) -90px 0 no-repeat;background-size:auto 100%;}\ .share-type-4{background:url(//game.gtimg.cn/images/sy/2016/miniweb/ingame/commsrc/shareicon.png) -135px 0 no-repeat;background-size:auto 100%;}\ .share-public-text {display: block;color: #aaa;font-size:14px;line-height:20px;padding-top:6px;}\ .share-dialog-close{ width:25px; height:25px; display:block; position:absolute; right:10px; top:10px; background:url(//game.gtimg.cn/images/user/cp/a20170922tipYYB/close-b.png) center center no-repeat; background-size:15px 15px; text-indent:-1000em; overflow:hidden}\ .share-layer{ width:100%; height:100%; position:fixed; left:0; top:0; z-index:2000; background:rgba(0,0,0,0.5) } `; document.getElementsByTagName('head')[0].appendChild(styleNode); const idObject = document.getElementById('div_share_ui'); if (idObject != null) { (_b = idObject.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(idObject); } const shareToQQ = ` <a href="javascript:;" onclick="javascript:${callback}(${SHARE_TYPE_MAP.QQ});">\ <span class="share-type share-type-3"></span>\ <span class="share-public-text">QQ好友</span>\ </a>\ `; const shareToQZone = ` <a href="javascript:;" onclick="javascript:${callback}(${SHARE_TYPE_MAP.QZone});">\ <span class="share-type share-type-4"></span>\ <span class="share-public-text">QQ空间</span>\ </a>\ `; const shareToTimeline = ` <a href="javascript:;" onclick="javascript:${callback}(${SHARE_TYPE_MAP.Timeline});">\ <span class="share-type share-type-1"></span>\ <span class="share-public-text">朋友圈</span>\ </a>\ `; const shareToWechat = ` <a href="javascript:;" onclick="javascript:${callback}(${SHARE_TYPE_MAP.Wechat});">\ <span class="share-type share-type-2"></span>\ <span class="share-public-text">微信好友</span>\ </a>\ `; const shareNode = document.createElement('div'); shareNode.id = 'div_share_ui'; shareNode.style.display = 'none'; shareNode.innerHTML = ` <div class="share-dialog-login">\ <a href="javascript:;" class="share-dialog-close" onclick="document.getElementById('div_share_ui').style.display='none';">关闭</a>\ <div class="share-choose-login">\ ${!((_c = shareObject.hideShareType) === null || _c === void 0 ? void 0 : _c.includes(SHARE_TYPE_MAP.Timeline)) ? shareToTimeline : ''} ${!((_d = shareObject.hideShareType) === null || _d === void 0 ? void 0 : _d.includes(SHARE_TYPE_MAP.Wechat)) ? shareToWechat : ''} ${!((_e = shareObject.hideShareType) === null || _e === void 0 ? void 0 : _e.includes(SHARE_TYPE_MAP.QQ)) ? shareToQQ : ''} ${!((_f = shareObject.hideShareType) === null || _f === void 0 ? void 0 : _f.includes(SHARE_TYPE_MAP.QZone)) ? shareToQZone : ''} </div>\ </div>\ <div class="share-layer" onclick="document.getElementById('div_share_ui').style.display='none';"></div> `; document.getElementsByTagName('body')[0].appendChild(shareNode); }; shareUiObj.initCommShareTip = function () { var _a, _b; const idObjectStyle = document.getElementById('div_share_tip_style'); if (idObjectStyle != null) { (_a = idObjectStyle.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(idObjectStyle); } const styleNode = document.createElement('style'); styleNode.id = 'div_share_tip_style'; styleNode.type = 'text/css'; if (isWzydShare) { styleNode.innerHTML = ` .tip-toc-sharetips { position: fixed; z-index: 9999; height: 100%; width: 100%; left: 0; top: 0; background: rgba(0,0,0,0.5); } .tip-toc-share-arrow{ background: url("https://image-1251917893.file.myqcloud.com/Esports/user/img/share-tip-arrow.png") no-repeat right center; background-size: .85rem .55rem; width: 100%; height: .55rem; margin-top: .16rem; } .tip-toc-share-box{ display: flex; position: fixed; top: .66rem; right: .62rem; } .tip-toc-sharetips .share-tip { height: .93rem; width: auto; background: url(https://image-1251917893.file.myqcloud.com/Esports/user/img/share-tip-bg.png) no-repeat; background-size: 100% .93rem; color: #fff; font-size: .28rem; position: relative; margin-left: .89rem; } .tip-toc-sharetips .share-tip>span{ display: block; max-width: 6rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; word-break: break-all; line-height: .93rem; } .tip-toc-sharetips .share-tip::before{ content: ''; position: absolute; top: 0; left: -.89rem; width: .89rem; height: .93rem; background: url(https://image-1251917893.file.myqcloud.com/Esports/user/img/share-tip-left.png) no-repeat; background-size: 100%; } .tip-toc-sharetips .share-tip::after{ content: ''; position: absolute; top: 0; right: -.61rem; width: .62rem; height: .93rem; background: url(https://image-1251917893.file.myqcloud.com/Esports/user/img/share-tip-right.png) no-repeat; background-size: 100%; }`; } else { styleNode.innerHTML = ` .tip-toc-sharetips { position: fixed; z-index: 9999; height: 100%; width: 100%; left: 0; top: 0; background: rgba(0,0,0,0.7); } .tip-toc-sharetips__arrow { position: absolute; top: .58rem; right: .58rem; width: 1.58rem; height: 1.52rem; background: url(https://image-1251917893.file.myqcloud.com/TIP_GameSystem_2020/toC/icon/share-arrow-2.png) center no-repeat; background-size: 1.58rem 1.52rem; } .tip-toc-sharetips__tip { padding: 2.1rem 2.2rem 0.1rem 0.2rem; text-align: right; font-size: .36rem; height: 2rem; color: #fff; } `; } document.getElementsByTagName('head')[0].appendChild(styleNode); const idObject = document.getElementById('div_share_tip'); if (idObject != null) { (_b = idObject.parentNode) === null || _b === void 0 ? void 0 : _b.removeChild(idObject); } const shareNode = document.createElement('div'); shareNode.id = 'div_share_tip'; shareNode.style.display = 'none'; if (isWzydShare) { shareNode.innerHTML = `<div class="tip-toc-sharetips"><div class="tip-toc-share-arrow" /><div class="tip-toc-share-box"><div class="share-tip"><span>${wzydShareText}</span></div></div></div>`; } else { shareNode.innerHTML = '<div class="tip-toc-sharetips"><div class="tip-toc-sharetips__arrow"></div><p class="tip-toc-sharetips__tip">点此分享</p></div>'; } document.getElementsByTagName('body')[0].appendChild(shareNode); const btn = document.getElementById('div_share_tip'); btn === null || btn === void 0 ? void 0 : btn.addEventListener('click', () => { const dom = document.getElementById('div_share_tip'); if (dom) { dom.style.display = 'none'; } }, false); }; shareUiObj.showCommShareUI = function () { const dom = document.getElementById('div_share_ui'); if (dom) { dom.style.display = 'block'; } }; shareUiObj.showCommShareTip = function () { const dom = document.getElementById('div_share_tip'); if (dom) { dom.style.display = 'block'; } }; /** * 打开自定义的分享UI组件 */ const openShareUI = function () { var _a, _b; // 提到函数中,方便测试 const env = getEnv(); if (env.isPvpApp || env.isTipApp) { ({ type: '1', title: shareObject.title, desc: shareObject.desc, image_url: shareObject.icon, share_url: shareObject.link, }); } else if (env.isInGame || env.isGHelper) { (_a = shareUiObj.openShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); } else if (env.isQQ || env.isWeixin) { (_b = shareUiObj.showCommShareTip) === null || _b === void 0 ? void 0 : _b.call(shareUiObj); } else { if (shareObject.link) { clipboardWeb(shareObject.link).then(() => { var _a, _b; (_a = shareObject.showToast) === null || _a === void 0 ? void 0 : _a.call(shareObject, ((_b = shareObject.tipMap) === null || _b === void 0 ? void 0 : _b.copyTextSuccess) || DEFAULT_TIP_MAP.copyTextSuccess); }) .catch(() => { var _a, _b; (_a = shareObject.showToast) === null || _a === void 0 ? void 0 : _a.call(shareObject, ((_b = shareObject.tipMap) === null || _b === void 0 ? void 0 : _b.copyTextFail) || DEFAULT_TIP_MAP.copyTextFail); showWindowNavigatorShareDialog(); }); } } }; function showWindowNavigatorShareDialog() { var _a, _b, _c, _d, _e; if (typeof ((_a = window === null || window === void 0 ? void 0 : window.navigator) === null || _a === void 0 ? void 0 : _a.share) === 'function') { window.navigator.share({ url: shareObject.link, text: shareObject.title, title: shareObject.title, }) .then(() => { console.info('[navigatorShare] success'); }) .catch(() => { console.info('[navigatorShare] fail'); }); } else { (_b = shareObject.showConfirmDialog) === null || _b === void 0 ? void 0 : _b.call(shareObject, { title: ((_c = shareObject.tipMap) === null || _c === void 0 ? void 0 : _c.dialogTitle) || DEFAULT_TIP_MAP.dialogTitle, message: ((_d = shareObject.tipMap) === null || _d === void 0 ? void 0 : _d.dialogMessage) || DEFAULT_TIP_MAP.dialogMessage, confirmButtonText: ((_e = shareObject.tipMap) === null || _e === void 0 ? void 0 : _e.dialogConfirmButton) || DEFAULT_TIP_MAP.dialogConfirmButton, showCancelButton: false, }); } } /** * 关闭自定义的分享UI组件 */ const closeShareUI = function () { const dom = document.getElementById('div_share_ui'); if (dom) { dom.style.display = 'none'; } const dom1 = document.getElementById('div_share_tip'); if (dom1) { dom1.style.display = 'none'; } }; /** * 初始化方法 obj:{title:'标题',desc:'描述',icon:'图标',link:'地址',callback:'', * isWzydShare:false(营地分享),wzydShareText:''(营地分享提示文案),forceHistoryMode:是否为history模式} * @param params 分享参数 */ const initShare = function (params = {}) { var _a, _b, _c, _d; const obj = params; obj.title = obj.title || ((_b = (_a = document.getElementsByTagName('title')) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.innerText); obj.desc = obj.desc || obj.title; obj.icon = obj.icon || DEFAULT_SHARE_ICON; obj.type = obj.type || null; obj.path = obj.path || null; obj.forceHistoryMode = (_c = obj.forceHistoryMode) !== null && _c !== void 0 ? _c : false; // 分享链接:移除 reporttk 参数 const link = obj.link || window.location.href; obj.link = removeUrlParams(link, ['reporttk'], obj.forceHistoryMode); shareObject = Object.assign(Object.assign({}, shareObject), obj); isWzydShare = (_d = obj.isWzydShare) !== null && _d !== void 0 ? _d : false; wzydShareText = obj.wzydShareText || '点击“...”分享链接'; // 提到函数中,方便测试 const env = getEnv(); if (env.isMsdkV5) { initMsdkV5Share(); } else if (env.isMsdk) { initMsdkShare(); } else if (env.isGHelper) { initGHelperShare(); } else if (env.isQQ) { initQQShare(); } else if (env.isMiniProgram) { initMiniProgramShare(); } else if (env.isWeixin) { initWeixinShare(); } else if (env.isPvpApp) { initPvpShare(); } else if (env.isTipApp) { initTipShare(); } else if (env.isSlugSdk) { initInGameShare(); } }; /** * 关闭 H5 分享入口 * @description 对有主动展示分享入口的环境进行关闭分享入口,GHelper=王者营地、Msdk/SlugSdk=游戏内,均无主动展示分享入口,不需要关闭 */ const hideShareBtn = function () { const env = getEnv(); if (env.isQQ) { // 手Q hideQQShareBtn(); } else if (env.isMiniProgram) ; else if (env.isWeixin) { // 微信 webview 环境 hideWeixinShareBtn(); } else if (env.isPvpApp) ; }; /** * 计算 base64 格式的图片大小 * @description 本质是计算字符串大小 * @param {string} base64url base64格式的图片地址 * @returns 图片大小,保留两位小数点单位 */ function calBase64Size(base64url) { let str = base64url.replace('data:image/png;base64,', ''); const equalIndex = str.indexOf('='); if (str.indexOf('=') > 0) { str = str.substring(0, equalIndex); } const strLength = str.length; const fileLength = parseInt(`${strLength - (strLength / 8) * 2}`, 10); return (fileLength / 1024).toFixed(2); } /** * 设置游戏内 MSDK 浏览器分享 * @description 通过游戏 App MSDK SDK 能力,进行设置分享信息 */ function initMsdkShare() { var _a; (_a = shareUiObj.initCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj, 'msdkShareDelegate'); shareUiObj.openShareUI = function () { var _a; (_a = shareUiObj.showCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); }; /* type:1(微信),2(朋友圈),3(QQ),4(QQ 空间) */ window.msdkShareDelegate = function (shareType) { var _a; (_a = shareObject.callback) === null || _a === void 0 ? void 0 : _a.call(shareObject, shareType); const type = shareType || 0; // msdk分享图片需要转Base64 https://wiki.ssl.msdk.qq.com/Android/webview.html#Android_JSInterface urlToBase64(shareObject.icon || '').then((imgData) => { var _a, _b, _c; let typeArr; const env = getEnv(); const imageDataSize = +calBase64Size(imgData); console.info('[msdkShareDelegate] imageDataSize: ', imageDataSize); const title = (_a = shareObject.title) === null || _a === void 0 ? void 0 : _a.replace(/\n|\r|"|\\/g, ''); const desc = (_b = shareObject.desc) === null || _b === void 0 ? void 0 : _b.replace(/\n|\r|"|\\/g, ''); // msdk分享图片,android图片大小不能超过10k if ((env.isIos && imageDataSize < 500) || (env.isAndroid && imageDataSize < 9)) { typeArr = { [SHARE_TYPE_MAP.Wechat]: `{"MsdkMethod":"WGSendToWeiXinWithUrl","scene":"0","title":"${title}","desc":"${desc}","imgData":"${imgData}","url":"${shareObject.link}","mediaTagName":"MSG_INVITE","messageExt":"${title}"}`, [SHARE_TYPE_MAP.Timeline]: `{"MsdkMethod":"WGSendToWeiXinWithUrl","scene":"1","title":"${title}","desc":"${desc}","imgData":"${imgData}","url":"${shareObject.link}","mediaTagName":"MSG_INVITE","messageExt":"${title}"}`, [SHARE_TYPE_MAP.QQ]: `{"MsdkMethod":"WGSendToQQ","scene":"2","title":"${title}","desc":"${desc}","imgData":"${imgData}","url":"${shareObject.link}"}`, [SHARE_TYPE_MAP.QZone]: `{"MsdkMethod":"WGSendToQQ","scene":"1","title":"${shareObject.title}","desc":"${desc}","imgData":"${imgData}","url":"${shareObject.link}"}`, }; } else { typeArr = { [SHARE_TYPE_MAP.Wechat]: `{"MsdkMethod":"WGSendToWeiXinWithUrl","scene":"0","title":"${title}","desc":"${desc}","url":"${shareObject.link}","mediaTagName":"MSG_INVITE","messageExt":"${title}"}`, [SHARE_TYPE_MAP.Timeline]: `{"MsdkMethod":"WGSendToWeiXinWithUrl","scene":"1","title":"${title}","desc":"${desc}","url":"${shareObject.link}","mediaTagName":"MSG_INVITE","messageExt":"${title}"}`, [SHARE_TYPE_MAP.QQ]: `{"MsdkMethod":"WGSendToQQ","scene":"2","title":"${title}","desc":"${desc}","url":"${shareObject.link}"}`, [SHARE_TYPE_MAP.QZone]: `{"MsdkMethod":"WGSendToQQ","scene":"1","title":"${title}","desc":"${desc}","url":"${shareObject.link}"}`, }; } if (typeof typeArr[type] === 'undefined') { return false; } const param = typeArr[type]; if (type === SHARE_TYPE_MAP.Wechat && shareObject.path) { openWeixinOpenLink(shareObject, () => { var _a; try { (_a = window.msdkShare) === null || _a === void 0 ? void 0 : _a.call(window, param); } catch (e) { console.info('[msdkShare] error: ', e); throw e; } }); } else { try { (_c = window.msdkShare) === null || _c === void 0 ? void 0 : _c.call(window, param); } catch (e) { console.info('[msdkShare] error: ', e); throw e; } } }); }; } /** * 设置游戏内 MSDK V5 浏览器分享 * @description 通过游戏 App MSDK SDK 能力,进行设置分享信息 */ function initMsdkV5Share() { var _a; (_a = shareUiObj.initCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj, 'msdkShareDelegate'); shareUiObj.openShareUI = function () { var _a; (_a = shareUiObj.showCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); }; /* type:1(微信),2(朋友圈),3(QQ),4(QQ 空间) */ window.msdkShareDelegate = function (shareType) { var _a, _b, _c, _d, _e; (_a = shareObject.callback) === null || _a === void 0 ? void 0 : _a.call(shareObject, shareType); const type = shareType || 0; // msdk分享图片需要转Base64 https://wiki.ssl.msdk.qq.com/Android/webview.html#Android_JSInterface const title = (_b = shareObject.title) === null || _b === void 0 ? void 0 : _b.replace(/\n|\r|"|\\/g, ''); const desc = (_c = shareObject.desc) === null || _c === void 0 ? void 0 : _c.replace(/\n|\r|"|\\/g, ''); // 定义常量 -START- const JSON_BEGIN = '{'; const JSON_END = '}'; const JSON_DOT = ','; const METHOD_SHARE = '"MsdkMethod":"shareWebView"'; const METHOD_SEND = '"MsdkMethod":"sendMsgWebView"'; const CHANNEL_QQ = '"channel":"QQ"'; const CHANNEL_WECHAT = '"channel":"WeChat"'; // 定义常量 -END- const DATA_SEND_LINK = `"actionReport":"MSG_INVITE","desc":"${desc}","imagePath":"${shareObject.icon}","link":"${shareObject.link}","messageExt":"messageExt","tailLogo":"","thumbPath":"${shareObject.icon}","title":"${title}","type":10001,"user":""`; const typeArr = { [SHARE_TYPE_MAP.Wechat]: JSON_BEGIN + CHANNEL_WECHAT + JSON_DOT + METHOD_SEND + JSON_DOT + DATA_SEND_LINK + JSON_END, [SHARE_TYPE_MAP.Timeline]: JSON_BEGIN + CHANNEL_WECHAT + JSON_DOT + METHOD_SHARE + JSON_DOT + DATA_SEND_LINK + JSON_END, [SHARE_TYPE_MAP.QQ]: JSON_BEGIN + CHANNEL_QQ + JSON_DOT + METHOD_SEND + JSON_DOT + DATA_SEND_LINK + JSON_END, [SHARE_TYPE_MAP.QZone]: JSON_BEGIN + CHANNEL_QQ + JSON_DOT + METHOD_SHARE + JSON_DOT + DATA_SEND_LINK + JSON_END, }; if (typeof typeArr[type] === 'undefined') { return false; } const env = getEnv(); const param = typeArr[type]; if (type === SHARE_TYPE_MAP.Wechat && shareObject.path) { openWeixinOpenLink(shareObject, () => { var _a, _b; try { // eslint-disable-next-line no-undef if (env.isAndroid) { (_a = window.msdkCall) === null || _a === void 0 ? void 0 : _a.call(window, param); } else { if (window.WebViewJavascriptBridge) { (_b = window.msdkCall) === null || _b === void 0 ? void 0 : _b.call(window, param); } else { document.addEventListener('WebViewJavascriptBridgeReady', () => { var _a; (_a = window.msdkCall) === null || _a === void 0 ? void 0 : _a.call(window, param); }, false); } } } catch (e) { console.info('[msdkShareDelegate] error: ', e); throw e; } }); } else { try { // eslint-disable-next-line no-undef if (env.isAndroid) { (_d = window.msdkCall) === null || _d === void 0 ? void 0 : _d.call(window, param); } else { if (window.WebViewJavascriptBridge) { (_e = window.msdkCall) === null || _e === void 0 ? void 0 : _e.call(window, param); } else { document.addEventListener('WebViewJavascriptBridgeReady', () => { var _a; (_a = window.msdkCall) === null || _a === void 0 ? void 0 : _a.call(window, param); }, false); } } } catch (e) { console.info('[msdkShareDelegate] error: ', e); throw e; } } }; } /** * 设置游戏内微社区浏览器分享 * @description 通过游戏 App 内微社区浏览器内置的 SDK 能力,进行设置分享信息 */ function initInGameShare() { var _a; (_a = shareUiObj.initCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj, 'slugSDKShareDelegate'); shareUiObj.openShareUI = function () { var _a; (_a = shareUiObj.showCommShareUI) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); }; /** * type:1(微信),2(朋友圈),3(QQ),4(QQ 空间) */ window.slugSDKShareDelegate = function (shareType) { var _a; (_a = shareObject.callback) === null || _a === void 0 ? void 0 : _a.call(shareObject, shareType); if (typeof window.customBrowserInterface === 'object') { switch (shareType) { case SHARE_TYPE_MAP.Wechat: if (shareObject === null || shareObject === void 0 ? void 0 : shareObject.path) { openWeixinOpenLink(shareObject, () => { window.customBrowserInterface.sendToWeixinWithUrl(2, shareObject.title, shareObject.desc, shareObject.link, shareObject.icon); }); } else { window.customBrowserInterface.sendToWeixinWithUrl(2, shareObject.title, shareObject.desc, shareObject.link, shareObject.icon); } break; case SHARE_TYPE_MAP.Timeline: window.customBrowserInterface.sendToWeixinWithUrl(1, shareObject.title, shareObject.desc, shareObject.link, shareObject.icon); break; case SHARE_TYPE_MAP.QQ: window.customBrowserInterface.sendToQQ(2, shareObject.title, shareObject.desc, shareObject.link, shareObject.icon); break; case SHARE_TYPE_MAP.QZone: window.customBrowserInterface.sendToQQ(1, shareObject.title, shareObject.desc, shareObject.link, shareObject.icon); break; } } else { console.info('[slugSDKShareDelegate] 未引用sdk'); } }; } /** * 设置王者营地App分享 * @description 设置分享信息 */ function initGHelperShare() { if (typeof GameHelper === 'undefined') { if (document.addEventListener) { document.addEventListener('GameHelperReady', onGameHelperReady, false); } else { onGameHelperReady(); } } else { onGameHelperReady(); } function onGameHelperReady() { shareUiObj.openShareUI = function () { try { GameHelper === null || GameHelper === void 0 ? void 0 : GameHelper.shareWebPage(shareObject.title, shareObject.desc, shareObject.icon, shareObject.link, shareObject.type); } catch (e) { console.info('[GameHelper.shareWebPage] error: ', e); } }; } } /** * 设置 QQ 分享 * @description 设置分享信息,用户需要手动点击右上角进行分享 */ function initQQShare() { var _a; (_a = shareUiObj.initCommShareTip) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); loader('https://pub.idqqimg.com/qqmobile/qqapi.js?_bid=2538', () => { var _a, _b; (_b = (_a = window === null || window === void 0 ? void 0 : window.mqq) === null || _a === void 0 ? void 0 : _a.ui) === null || _b === void 0 ? void 0 : _b.setOnShareHandler( // http://mqq.oa.com/api.html#js-mqq-core (type) => { if (type == 0 || type == 1 || type == 2 || type == 3 || type == 11) { const param = { title: shareObject.title, desc: shareObject.desc, share_type: type, share_url: shareObject.link, image_url: shareObject.icon, back: true, uinType: 0, }; const callback = function () { var _a; (_a = shareObject.callback) === null || _a === void 0 ? void 0 : _a.call(shareObject); // alert(result.retCode); }; // eslint-disable-next-line no-undef window.mqq.ui.shareMessage(param, callback); } }); }); } /** * 关闭QQ分享入口 * @description 在QQ内打开H5,关闭通过右上角唤起的功能面板中的分享入口 */ function hideQQShareBtn() { loader('https://open.mobile.qq.com/sdk/qqapi.js?_bid=152', () => { var _a, _b, _c; (_c = (_b = (_a = window === null || window === void 0 ? void 0 : window.mqq) === null || _a === void 0 ? void 0 : _a.ui) === null || _b === void 0 ? void 0 : _b.setWebViewBehavior) === null || _c === void 0 ? void 0 : _c.call(_b, { actionButton: 0, // 隐藏 webview右上角按钮 }); }); } /** * 设置微信分享 * @description 调用提供的 JS API 进行设置分享,用户需要手动点击右上角进行分享 */ function initWeixinShare() { var _a, _b; (_a = shareUiObj.initCommShareTip) === null || _a === void 0 ? void 0 : _a.call(shareUiObj); (_b = shareObject.configWx) === null || _b === void 0 ? void 0 : _b.call(shareObject, [ 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone', 'updateAppMessageShareData', 'updateTimelineShareData', ], ['wx-open-launch-weapp']).then((wx) => { // 处理分享参数 const tmp = { title: shareObject.title, desc: shareObject.desc, link: shareObject.link || '', imgUrl: shareObject.icon, type: '', dataUrl: '', success(info) { var _a; (_a = shareObject.callback) === null || _a === void 0 ? void 0 : _a.call(shareObject); console.info('[initWeixinShare] callback success: ', info); }, cancel() { }, fail(info) { console.info('[initWeixinShare] callback fail: ', info); }, }; if (tmp.link.indexOf('?') === -1) { tmp.link = `${tmp.link}?sharect=${new Date().getTime()}`; } else if (tmp.link.indexOf('sharect') === -1) { tmp.link = `${tmp.link}&sharect=${new Date().getTime()}`; } wx.onMenuShareTimeline(tmp); wx.onMenuShareAppMessage(tmp); wx.onMenuShareQQ(tmp); wx.onMenuShareQZone(tmp); // 请注意,原有的 wx.onMenuShareTimeline、wx.onMenuShareAppMessage、wx.onMenuShareQQ、wx.onMenuShareQZone 接口, // 即将废弃。请尽快迁移使用客户端6.7.2及JSSDK 1.4.0以上版本支持的 wx.updateAppMessageShareData、wx.updateTimelineShareData接口。 // 文档地址 https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html wx === null || wx === void 0 ? void 0 : wx.ready(() => { var _a, _b; (_a = wx === null || wx === void 0 ? void 0 : wx.updateAppMessageShareData) === null || _a === void 0 ? void 0 : _a.call(wx, tmp); console.info('[initWeixinShare] info: ', tmp); (_b = wx === null || wx === void 0 ? void 0 : wx.updateTimelineShareData) === null || _b === void 0 ? void 0 : _b.call(wx, tmp); }); }).catch((error) => { console.info('[initWeixinShare] catch error: ', error); }); } /** * 关闭微信分享入口 * @description 在微信内打开H5页面,关闭通过右上角唤起的功能面板中的分享入口 */ function hideWeixinShareBtn() { var _a; (_a = shareObjec