export class Communication { constructor() { this.webViewObj = null; this.messageHandlers = {}; } setWebView(webView) { this.webViewObj = webView; } sendToH5(action, data = {}) { if (!this.webViewObj) { console.error('webViewObj is not initialized'); return; } const message = JSON.stringify({ action, data }); // 调用 H5 端的 window.handleMessage 函数 this.webViewObj.evalJS(`window.handleMessage(${JSON.stringify(message)})`); } registerHandler(action, handler) { this.messageHandlers[action] = handler; } handleMessage(message) { try { const { action, data } = JSON.parse(message); if (this.messageHandlers[action]) { this.messageHandlers[action](data); } else { console.warn('Unknown action:', action); } } catch (error) { console.error('Failed to handle message:', error); } } }