You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
oa-base/utils/communication.js

39 lines
1.0 KiB
JavaScript

1 month ago
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);
}
}
}