111 lines
3.0 KiB
JavaScript
111 lines
3.0 KiB
JavaScript
/**
|
|
* Game Iframe SDK - Message Handler
|
|
* Xử lý message từ iframe
|
|
*/
|
|
import { MESSAGE_TYPES } from './types';
|
|
import { EventEmitter } from './EventEmitter';
|
|
/**
|
|
* MessageHandler - Xử lý incoming messages từ iframe
|
|
*/
|
|
export class MessageHandler extends EventEmitter {
|
|
constructor(config) {
|
|
super();
|
|
this.boundHandler = null;
|
|
this.isListening = false;
|
|
this.config = config;
|
|
}
|
|
/**
|
|
* Start listening for messages
|
|
*/
|
|
start() {
|
|
if (this.isListening) {
|
|
return this;
|
|
}
|
|
this.boundHandler = this.handleMessage.bind(this);
|
|
window.addEventListener('message', this.boundHandler);
|
|
this.isListening = true;
|
|
this.log('MessageHandler started');
|
|
return this;
|
|
}
|
|
/**
|
|
* Stop listening for messages
|
|
*/
|
|
stop() {
|
|
if (this.boundHandler) {
|
|
window.removeEventListener('message', this.boundHandler);
|
|
this.boundHandler = null;
|
|
}
|
|
this.isListening = false;
|
|
this.log('MessageHandler stopped');
|
|
return this;
|
|
}
|
|
/**
|
|
* Check if handler is listening
|
|
*/
|
|
isActive() {
|
|
return this.isListening;
|
|
}
|
|
/**
|
|
* Handle incoming message
|
|
*/
|
|
handleMessage(event) {
|
|
// Origin check
|
|
if (!this.isOriginAllowed(event.origin)) {
|
|
return;
|
|
}
|
|
const { type, data } = event.data || {};
|
|
if (!type)
|
|
return;
|
|
this.log(`Received: ${type}`, data);
|
|
try {
|
|
switch (type) {
|
|
case MESSAGE_TYPES.GAME_READY:
|
|
this.emit('gameReady', undefined);
|
|
break;
|
|
case MESSAGE_TYPES.ANSWER_REPORT:
|
|
// Raw data pass-through
|
|
this.emit('answerReport', data);
|
|
break;
|
|
case MESSAGE_TYPES.FINAL_RESULT:
|
|
// Raw data pass-through
|
|
this.emit('finalResult', data);
|
|
break;
|
|
case MESSAGE_TYPES.GET_LEADERBOARD:
|
|
this.emit('leaderboardRequest', { top: data?.top || 10 });
|
|
break;
|
|
default:
|
|
this.emit('unknownMessage', { type, data });
|
|
break;
|
|
}
|
|
}
|
|
catch (error) {
|
|
const err = error;
|
|
this.emit('error', { message: `Error handling ${type}`, error: err });
|
|
}
|
|
}
|
|
/**
|
|
* Check if origin is allowed
|
|
*/
|
|
isOriginAllowed(origin) {
|
|
if (this.config.acceptedOrigin === '*') {
|
|
return true;
|
|
}
|
|
return origin === this.config.acceptedOrigin;
|
|
}
|
|
/**
|
|
* Debug log
|
|
*/
|
|
log(message, data) {
|
|
if (this.config.debug) {
|
|
console.log('[MessageHandler]', message, data ?? '');
|
|
}
|
|
}
|
|
/**
|
|
* Cleanup
|
|
*/
|
|
destroy() {
|
|
this.stop();
|
|
this.removeAllListeners();
|
|
}
|
|
}
|
|
//# sourceMappingURL=MessageHandler.js.map
|