const WebviewEvents = { /** * 获取平台信息 */ GET_PLATFORM: 'getPlatform', /** * 获取状态栏高度 */ GET_STATUS_BAR_HEIGHT: 'getStatusBarHeight', /** * 扫码 */ SCAN: 'scan', /** * 苹果支付 */ APPLE_PAY: 'applePay', APPLE_PAY_RESTORE: 'applePayRestore', // 微信是否安装 CHECK_WECHAT_INSTALLED: 'checkWechatInstalled', GET_UPGRADE_INFO: 'getUpgradeInfo', DOWNLOAD_UPGRADE: 'downloadAndInstall', OPEN_IFRAME: 'openIframe' } function resetWindowCallback(callbackEvent) { window[callbackEvent] = null; delete window[callbackEvent]; } async function getWebviewCallback(event, args) { if (!uni.webView) { return Promise.reject(new Error('uni环境异常,请检查uni.webview是否正确引入')); } if (window.platform === 'h5') { return Promise.reject(new Error('请在app中使用')); } const callbackEvent = `webviewCallback_${event}`; try { return await new Promise((resolve, reject) => { window[callbackEvent] = (data) => { resolve(data); resetWindowCallback(callbackEvent); }; uni.webView.postMessage({ data: { action: event, data: { callbackAction: callbackEvent, data: args } } }); }); } catch (error) { return Promise.reject(new Error('webview初始化失败,请检查是否正确引入uni.webview')); } } class WebviewBridge { constructor() { } getPaltform() { return getWebviewCallback(WebviewEvents.GET_PLATFORM); } scan(...args) { return getWebviewCallback(WebviewEvents.SCAN, args); } applePay(...args) { return getWebviewCallback(WebviewEvents.APPLE_PAY, args); } applePayRestore(...args) { return getWebviewCallback(WebviewEvents.APPLE_PAY_RESTORE, args); } checkWechatInstalled(...args) { return getWebviewCallback(WebviewEvents.CHECK_WECHAT_INSTALLED, args); } getStatusBarHeight() { return getWebviewCallback(WebviewEvents.GET_STATUS_BAR_HEIGHT); } getUpgradeInfo(...args) { return getWebviewCallback(WebviewEvents.GET_UPGRADE_INFO, args); } openIframe(...args) { return getWebviewCallback(WebviewEvents.OPEN_IFRAME, args); } downloadUpgrade(url, progressCb) { window.onDownloadProgress = progressCb; return getWebviewCallback(WebviewEvents.DOWNLOAD_UPGRADE, { url, progressCb: 'onDownloadProgress' }); } } const webviewBridge = new WebviewBridge(); window.webviewBridge = webviewBridge;