Fix duplicate message listeners

pull/21833/head
Richard Lewis 2018-01-18 13:16:06 +00:00
parent 910623d287
commit 23bef68a8f
2 changed files with 14 additions and 10 deletions

View File

@ -178,6 +178,10 @@ export default class WidgetMessaging extends MatrixPostMessageApi {
constructor(widgetId, targetWindow) {
super(targetWindow);
this.widgetId = widgetId;
this.startListening = this.startListening.bind(this);
this.stopListening = this.stopListening.bind(this);
this.onMessage = this.onMessage.bind(this);
}
exec(action) {
@ -206,9 +210,11 @@ export default class WidgetMessaging extends MatrixPostMessageApi {
* Register widget message event listeners
*/
startListening() {
this.start();
if (global.mxWidgetMessagingListenerCount === 0) {
window.addEventListener("message", (evt) => this.onMessage(evt), false);
// Start postMessage API listener
this.start();
// Start widget specific listener
window.addEventListener("message", this.onMessage, false);
}
global.mxWidgetMessagingListenerCount += 1;
}
@ -217,10 +223,12 @@ export default class WidgetMessaging extends MatrixPostMessageApi {
* De-register widget message event listeners
*/
stopListening() {
this.stop();
global.mxWidgetMessagingListenerCount -= 1;
if (global.mxWidgetMessagingListenerCount === 0) {
window.removeEventListener("message", () => this.onMessage);
// Stop widget specific listener
window.removeEventListener("message", this.onMessage, false);
// Stop postMessage API listener
this.stop();
}
if (global.mxWidgetMessagingListenerCount < 0) {
// Make an error so we get a stack trace

View File

@ -171,12 +171,8 @@ export default class AppTile extends React.Component {
// Widget postMessage listeners
try {
if (this.widgetMessaging) {
this.widgetMessaging.stopListening();
this.widgetMessaging.removeEndpoint(this.props.id, this.props.url);
} else {
console.warn('WidgetMessaging not initialised. Not stopping.');
}
this.widgetMessaging.stopListening();
this.widgetMessaging.removeEndpoint(this.props.id, this.props.url);
} catch (e) {
console.error('Failed to stop listening for widgetMessaging events', e.message);
}