35 lines
902 B
JavaScript
35 lines
902 B
JavaScript
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) {
|
|
const { action, data = {} } = message
|
|
if (this.messageHandlers[action]) {
|
|
this.messageHandlers[action](data);
|
|
} else {
|
|
console.warn('Unknown action:', action);
|
|
}
|
|
}
|
|
}
|
|
|